C# 相当于 Scala Promise

C# equivalent of Scala Promise

在 scala 中有 PromisesFutures。使用 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

如何使用 C# 实现类似的结果 Task API?我在文档中找不到任何等效内容。

我想在测试中使用它,模拟对象 returns 这样 Task 然后我检查在任务完成之前是否满足某些条件,然后完成它并检查另一个条件。

您可以使用 TaskCompletionSource<T> :

void Main()
{
    var tcs = new TaskCompletionSource<bool>();
    tcs.SetResult(true);
    Console.WriteLine(tcs.Task.IsCompleted); // prints true.
}

我认为您需要的是任务。您可以找到更多信息 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;

您可以使用 try/catch 来帮助您管理可能的错误。
要强制输出值,您可以使用另一个用户上面提到的 TaskCompletionSource

TaskCompletionSource

正如 Yuval 所说,TaskCompletionSource 是一个 Promise 而 Task 是一个 Future 但请注意,在 C# 中 你应该很少使用 TaskCompletionSource .

原因是 TaskCompletionSource 用于将非任务 API 转换为基于任务的任务。在 C# 中,几乎所有 API 都已经 Task-returning.

因此,尽管它们很相似 - 在 C# 中,您很少需要 TaskCompletionSource(其中 Promise 在 scala 中很常见)。

您可能正在寻找 FromResult

如果你想创建一个模拟 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
}