How to start multiple threads and wait for them to complete

I want to write a method that starts multiple threads, and I want to be sure that they are all complete using async/await until the end of my method. How can i do this?

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 can i do this?

+4
source share
2 answers

Your requirement does not match your code example. You have tagged your async method, which means you want this method to be able to return before it completes its work. However, you say that you want him to return only after all the work is done.

Thus, if you want your method to be synchronous, do not use async and manually wait for all 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); 
+7
source

async way to do this is to make your method return a Task , and the caller of this method will then be await (or Wait() ). Then your method might look like this:

 private async Task SomeWork() { var a = doWork1(); var b = doWork2(); var c = doWork3(); var d = doWork4(); ... await Task.WhenAll(a, b, c, d); } 
+8
source

Source: https://habr.com/ru/post/1403434/


All Articles