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.
using System;
using System.Threading;
public class Test
{
public static void Main()
{
Console.WriteLine("Main Thread Started");
//Spawn a thread
Thread t1=new Thread(Start);
t1.Start();
Console.WriteLine("Main Thread Ends");
}
static void Start()
{
Console.WriteLine("child Thread Started");
for(int i=0;i<100;i++)
{
Console.Write(i);
}
Console.WriteLine("child Thread Ends");
}
}
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.
using System;
using System.Threading;
public class Test
{
public static void Main()
{
Console.WriteLine("Main Thread Started");
//Spawn a thread
Thread t1=new Thread(Start);
t1.Start();
//Wait for thread t1 to finish
t1.Join();
Console.WriteLine("Main Thread Ends");
}
static void Start()
{
Console.WriteLine("child Thread Started");
for(int i=0;i<100;i++)
{
Console.WriteLine(i);
}
Console.WriteLine("child Thread Ends");
}
}
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.