C#中的Promise等效项 [英] Promise equivalent in C#
问题描述
在Scala中,有一个Promise类可用于手动完成Future.我正在寻找C#的替代方法.
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);
我知道这可能不是C#的正确模式,但是即使模式有所不同,我也无法找到实现同一目标的合理方法.
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.
请注意,async
/await
在这里无济于事,因为我没有要等待的任务!我只能访问将在另一个线程上运行的处理程序.
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.
推荐答案
在C#中:
-
Task<T>
是未来(或Task
是单位返回的未来). -
TaskCompletionSource<T>
是一个承诺.
Task<T>
is a future (orTask
for a unit-returning future).TaskCompletionSource<T>
is a promise.
因此您的代码将这样翻译:
So your code would translate as such:
// var promise = new Promise<MyResult>;
var promise = new TaskCompletionSource<MyResult>();
// handlerMyEventsWithHandler(msg => promise.Complete(msg););
handlerMyEventsWithHandler(msg => promise.TrySetResult(msg));
// var myResult = promise.Future.Await(2000);
var completed = await Task.WhenAny(promise.Task, Task.Delay(2000));
if (completed == promise.Task)
; // Do something on timeout
var myResult = await completed;
Assert.Equals("my header", myResult.Header);
定时异步等待"有点尴尬,但在现实世界的代码中也很少见.对于单元测试,我只需要进行常规的异步等待:
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:
var promise = new TaskCompletionSource<MyResult>();
handlerMyEventsWithHandler(msg => promise.TrySetResult(msg));
var myResult = await promise.Task;
Assert.Equals("my header", myResult.Header);
这篇关于C#中的Promise等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!