Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multithreading while blocking main thread

How do I start 2 or more threads all at once and block the main thread until the others threads are complete?

like image 227
user125155 Avatar asked Dec 09 '22 19:12

user125155


1 Answers

From the main thread, call Thread.Join on each of the other threads.

(EDIT: Now you've specified C#, there's no need for the platform agnostic comment.)

For example:

Thread t1 = new Thread(FirstMethod).Start();
Thread t2 = new Thread(SecondMethod).Start();

t1.Join();
t2.Join();

It doesn't matter what order you call Join in, if you only want to wait until they've all finished. (If you want to continue when any of them have finished, you need to get into the realm of wait handles.)

like image 71
Jon Skeet Avatar answered Dec 24 '22 07:12

Jon Skeet