Wait for the other threads to complete

Description



In the below example, there are 2 threads: thdFirstThread and thdSecondThread. "thdFirstThread" is used to call "Display1to5" function and "thdSecondThread" is used to call "Display5to10" function.
Below statement makes the first thread to wail till the second thread finishes its processing.
thdFirstThread.Join();


class clsThreading
{
public static void Main(string[] args)
{
//Passing function "Display1to5" to ThreadStart Delegate
ThreadStart thdstObj1 = new ThreadStart(Display1to5);
//Passing function "Display5to10" to ThreadStart Delegate
ThreadStart thdstObj2 = new ThreadStart(Display5to10);

//Passed thdstObj1 delegate created above to the Thread Object.
Thread thdFirstThread = new Thread(thdstObj1);
//Passed thdstObj2 delegate created above to the Thread Object.
Thread thdSecondThread = new Thread(thdstObj2);

//Started First thread.
thdFirstThread.Start();
//Started Second thread.
thdSecondThread.Start();

//thdFirstThread thread waits till the completion of thdSecondThread thread.
thdFirstThread.Join();
Console.WriteLine("Exiting Main");
Console.ReadLine();
}
public static void Display1to5()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("{0}", i);
}
}
public static void Display5to10()
{
for (int i = 6; i <= 10; i++)
{
Console.WriteLine("{0}", i);
}
}
}


Comments

Author: Pawan Awasthi04 Apr 2011 Member Level: Gold   Points : 0

nice example to understand for the beginners...

Thanks



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: