简体   繁体   中英

C# equivalent of Scala Promise

In scala there are Promises and Futures . With Promise I can control when Future completes, ie

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? 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.

You can use 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.
To force the output value you can use TaskCompletionSource as mentioned above by another user.

It's TaskCompletionSource

Like Yuval said, TaskCompletionSource is a Promise and a Task is a Future but note that in C# you should rarely use TaskCompletionSource .

The reason is that TaskCompletionSource is used to convert a non-task API to a task based one. In C#, almost all APIs are already Task -returning.

So while they're similar - in C# you rarely need TaskCompletionSource (where Promise in scala is common).

You're probably looking for 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:

void Fn()
{
    var task = Task.FromResult(true);
    Console.WriteLine(task.IsCompleted); // prints true.
    Console.WriteLine(task.Result); // prints true. a ""blocking"" API
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM