Home
Map
Thread Join MethodUse the Join method on an array of threads to wait for all threads to finish.
C#
This page was last reviewed on May 19, 2022.
Join. In .NET we use methods to perform threading. On the Thread type, we find the Join instance method. It enables us to wait until a thread finishes.
Method use. We use the C# Join method on an array of threads to implement useful threading functionality. Join() can be called on a Thread instance.
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.
Detail When the loop where we call Join completes, all of the threads have completed.
Thread.Sleep
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); } }
DONE: 10001
The results show the effectiveness of threading. 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, you can use the ThreadPool type. This has further improvements that can improve CPU utilization.
ThreadPool
Some notes. You do not need to use Join in an array or List, but it is often desirable to. With parallel execution, you can make many programs faster. Join() serves an essential role.
ThreadStart
A summary. Join() from the .NET System.Threading namespace is an important C# threading method. It provides blocking functionality that waits for the specified thread to complete.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 19, 2022 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.