Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Thread Join Method

This C# article shows how to call Join on multiple 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 four threads and then calls a parameterless 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.


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));
	// Join all the threads.
	for (int i = 0; i < array.Length; i++)
	Console.WriteLine("DONE: {0}", stopwatch.ElapsedMilliseconds);

    static void Start()
	// This method takes ten seconds to terminate.


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.

Note: The extra millisecond in the result is probably because there is dust in my computer.

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.


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.