问题描述
在 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
是未来(或Task
是返回单位的未来).TaskCompletionSource
是一个承诺.
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 等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!