Why to use C# Thread join method

(Last Updated On: January 19, 2017)

Answer: C# thread join() method is used to join multiple threads or in simple way, to make a thread wait for its all child threads to finish their task. For example, in below program, in main, if we use thread.join() method, main thread will wait to finish all child threads and till then main thread will be alive.

If we don’t use join() method in main() thread, main thread may die before child thread.

Below two C# multithreading examples are given, that is one without using thread join() method and another using join method.

Thread program example without using join method

In below C# source code, main thread will not wait for all threads to finish.

 

Output

Main Thread Started
Main Thread Ends
child Thread Started
0 1 2 …99
child Thread Ends

Note that in above output main thread is already dead without waiting for child thread to finish as we have not used join method.

Thread program example using join method:

In below C# source code, main or parent thread will join multiple threads. means, main thread will wait for all threads to finish before continuing.

 

Output:

Main Thread Started
child Thread Started
0 1 2 …99
child Thread Ends
Main Thread Ends

 

NOTE:

1 – If a thread have multiple child threads and it wants to wait for all threads to finish then we have to apply join on all threads for example

t1.Start();
t2.Start();
t3.Start(); etc.

2- To notice the output, if main thread die before Child  thread without using join, put long running task to child threads.