[英]C# equivalent of Scala Promise
In scala there are Promises
and Futures
. 在scala中有
Promises
和Futures
。 With Promise
I can control when Future
completes, ie 有了
Promise
我可以控制Future
何时完成,即
val p = Promise[Int]()
val fut: Future[Int] = p.future // I already have a running Future here
// here I can do whatever I want and when I decide Future should complete, I can simply say
p success 7
// and fut is now completed with value 7
How can I achieve similar results with C# Task
API? 如何使用C#
Task
API获得类似的结果? I couldn't find anything equivalent in docs. 我在文档中找不到任何相同的东西。
I want to use this in a test, mocked object returns such Task
and then I check if some condition holds before task completes, then complete it and check another condition. 我想在测试中使用它,模拟对象返回这样的
Task
然后在任务完成之前检查某些条件是否成立,然后完成它并检查另一个条件。
You can use TaskCompletionSource<T>
: 您可以使用
TaskCompletionSource<T>
:
void Main()
{
var tcs = new TaskCompletionSource<bool>();
tcs.SetResult(true);
Console.WriteLine(tcs.Task.IsCompleted); // prints true.
}
I think what you need are Tasks. 我认为你需要的是任务。 You can find more info here .
你可以在这里找到更多信息。
Task<int> futureB = Task.Factory.StartNew<int>(() => F1(a));
int c = F2(a);
int d = F3(c);
int f = F4(futureB.Result, d);
return f;
You can use try/catch to help you manage possible error. 您可以使用try / catch来帮助您管理可能的错误。
To force the output value you can use TaskCompletionSource
as mentioned above by another user. 要强制输出值,您可以使用另一个用户如上所述的
TaskCompletionSource
。
TaskCompletionSource
TaskCompletionSource
Like Yuval said, TaskCompletionSource
is a Promise and a Task
is a Future
but note that in C# you should rarely use TaskCompletionSource
. 就像Yuval所说,
TaskCompletionSource
是一个Promise,一个Task
是一个Future
但请注意,在C#中你应该很少使用TaskCompletionSource
。
The reason is that TaskCompletionSource
is used to convert a non-task API to a task based one. 原因是
TaskCompletionSource
用于将非任务API转换为基于任务的API。 In C#, almost all APIs are already Task
-returning. 在C#中,几乎所有API都已经是
Task
-returning。
So while they're similar - in C# you rarely need TaskCompletionSource
(where Promise
in scala is common). 所以虽然它们很相似 - 在C#中你很少需要
TaskCompletionSource
(scala中的Promise
很常见)。
FromResult
FromResult
If you want to create a mock API with tasks you don't want TaskCompletionSource, you want FromResult
which creates a completed task based on a value: 如果你想创建任务的模拟API你不想TaskCompletionSource,你想
FromResult
它创建基于值完成的任务:
void Fn()
{
var task = Task.FromResult(true);
Console.WriteLine(task.IsCompleted); // prints true.
Console.WriteLine(task.Result); // prints true. a ""blocking"" API
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.