In Scala there is a Promise class that could be used to complete a Future manually. I am looking for an alternative in C#.
I am writing a test and I want it to look it similar to this:
// var MyResult has a field `Header`
var promise = new Promise<MyResult>;
handlerMyEventsWithHandler( msg =>
promise.Complete(msg);
);
// Wait for 2 seconds
var myResult = promise.Future.Await(2000);
Assert.Equals("my header", myResult.Header);
I understand that this is probably not the right pattern for C#, but I couldn't figure out a reasonable way to achieve the same thing even with somewhat different pattern.
EDIT: please note, that async
/await
doesn't help here, as I don't have a Task to await! I just have an access to a handler that will be run on another thread.
The rough C# equivalent without third-party libraries would be:
Note that it is usually best to use the
await
/async
to as high a level as possible. Accessing theResult
of aTask
or usingWait
can in some cases introduce deadlocks.In C#:
Task<T>
is a future (orTask
for a unit-returning future).TaskCompletionSource<T>
is a promise.So your code would translate as such:
The "timed asynchronous wait" is a bit awkward, but it's also relatively uncommon in real-world code. For unit tests, I would just do a regular asynchronous wait:
This is the old school way of doing Promises.
Back then i believe it was called synchronization :)
Just for Completeness - to large for a comment.
I agree with Stephen Cleary's answer.
But if you are building a facade around some legacy code this can be used to wrap old API's in a Task like:
Try looking into the async model. Tasks are the nearest equivalent in c#.
Here's a link to an MS Article explaining their use.
You can use C# Promises library
Open sourced on Github: https://github.com/Real-Serious-Games/C-Sharp-Promise
Available on NuGet: https://www.nuget.org/packages/RSG.Promise/