HomeSearch

C# Thread Join Method (Join Array of Threads)

This C# article uses the Join method on an array of threads. It requires System.Threading.
Join waits for a thread to finish. On the Thread type, we find the Join instance method. It enables us to wait until the thread finishes. We use the Join method on an array of threads to implement useful threading functionality.
Example. This program creates an array of 4 threads and then calls a method on each thread. The method called (Start) requires 10,000 milliseconds to complete because it calls Thread.Sleep.

Next: We loop again through the threads, which have now been started, and call Join on each of them.

And: The Join method causes the execution to stop until that thread terminates.

Therefore: When the loop where we call Join completes, all of the threads have completed.

Sleep
C# program that calls Join method on Thread using System; using System.Diagnostics; using System.Threading; class Program { static void Main() { var stopwatch = Stopwatch.StartNew(); // Create an array of Thread references. Thread[] array = new Thread[4]; for (int i = 0; i < array.Length; i++) { // Start the thread with a ThreadStart. array[i] = new Thread(new ThreadStart(Start)); array[i].Start(); } // Join all the threads. for (int i = 0; i < array.Length; i++) { array[i].Join(); } Console.WriteLine("DONE: {0}", stopwatch.ElapsedMilliseconds); } static void Start() { // This method takes ten seconds to terminate. Thread.Sleep(10000); } } Output DONE: 10001
The results of this program demonstrate the effectiveness of the threading and the Join method. The four threads would have slept for ten seconds each, but the entire program only took ten seconds total to execute.
ThreadPool. Instead of using a Thread array and implementing the threading functionality by yourself, you can use the ThreadPool type. This has further improvements that handle threads that finish before other threads, probably improving performance.ThreadPool
Summary. Most threading libraries provide a Join procedure, and the .NET System.Threading namespace functionality is no different. This method provides blocking functionality that waits for the specified thread to complete.

And: You do not need to use Join in an array or List, but it is often desirable to.

Tip: With parallel execution, you can make many programs faster and the Join method serves an essential role in this goal.

ThreadStart
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls