Created
June 24, 2015 21:57
-
-
Save qbit86/3a35d62db16c480dbca9 to your computer and use it in GitHub Desktop.
Promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Squisqula | |
{ | |
public sealed class Promise<T> | |
{ | |
public void SetResult(T result) | |
{ | |
_result = new T[] { result }; | |
var handler = Completed; | |
if (handler != null) | |
{ | |
handler(this, EventArgs.Empty); | |
} | |
} | |
public Future<T> Future { get { return new Future<T>(this); } } | |
internal T Result | |
{ | |
get | |
{ | |
if (_result.Length == 0) | |
throw new InvalidOperationException("Promise is not completed."); | |
return _result[0]; | |
} | |
} | |
internal bool IsCompleted { get { return _result.Length > 0; } } | |
internal event EventHandler Completed; | |
private T[] _result = new T[0]; // Hand-made Option<T>. | |
} | |
public sealed class Future<T> | |
{ | |
internal Future(Promise<T> promise) | |
{ | |
_promise = promise; | |
} | |
public bool IsCompleted { get { return _promise.IsCompleted; } } | |
public T Result | |
{ | |
get | |
{ | |
if (!_promise.IsCompleted) | |
throw new InvalidOperationException("Future is not completed."); | |
return _promise.Result; | |
} | |
} | |
public event EventHandler Completed | |
{ | |
add { _promise.Completed += value; } | |
remove { _promise.Completed -= value; } | |
} | |
private readonly Promise<T> _promise; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment