How can I create multiple threads and wait for all of them to complete?
Behind the scenes it is using default JVM's fork join pool which means that it will wait for all the threads to finish before continuing.
Barriers. Barriers are a synchronization mechanism that can be used to coordinate multiple threads working in parallel. A barrier allows each thread to wait until all cooperating threads have reached the same point, and then continue executing from there.
It depends which version of the .NET Framework you are using. .NET 4.0 made thread management a whole lot easier using Tasks:
class Program { static void Main(string[] args) { Task task1 = Task.Factory.StartNew(() => doStuff()); Task task2 = Task.Factory.StartNew(() => doStuff()); Task task3 = Task.Factory.StartNew(() => doStuff()); Task.WaitAll(task1, task2, task3); Console.WriteLine("All threads complete"); } static void doStuff() { //do stuff here } }
In previous versions of .NET you could use the BackgroundWorker
object, use ThreadPool.QueueUserWorkItem()
, or create your threads manually and use Thread.Join()
to wait for them to complete:
static void Main(string[] args) { Thread t1 = new Thread(doStuff); t1.Start(); Thread t2 = new Thread(doStuff); t2.Start(); Thread t3 = new Thread(doStuff); t3.Start(); t1.Join(); t2.Join(); t3.Join(); Console.WriteLine("All threads complete"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With