I want to write a method that run multiple threads and I want before end of my method I have been assured that all of them are complete using async/await
. how I can do this?
please consider this psudo code:
private async void SomeWork()
{
var a = doWork1();
var b = doWork2();
var c = doWork3();
var d = doWork4();
...
//I want to assure that all of above thread are complete using `C#-5` new features
}
How I can do this?
Your requirement does not match your code example: You marked your method async
, which means that you want this method to be able to return before it has completed its work. Yet, you say that you want it to return only after all the work has been done.
Thus, if you want your method to be synchronous, don't use async
and manually wait for all the tasks to complete:
private void SomeWork()
{
var a = doWork1();
var b = doWork2();
var c = doWork3();
var d = doWork4();
...
a.Wait();
b.Wait();
c.Wait();
d.Wait();
}
or, more elegantly:
Task.WaitAll(a, b, c, d);