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.
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
.
Join
on each of them.Join
method causes the execution to stop until that thread terminates.Join
completes, all of the threads have completed.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.
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.