Bak2Basics: Threading: Waiting for another thread to finish.

Posted on 10/17/2006 @ 3:27 PM in #Bak2Basics by | Feedback | 55927 views

So the topic of synchronizing threads is quite huge, so I am going to write up numerous short articles on how you can use various tips and tricks to do so.

The first way to do so is – You wait for another thread to finish. And how do you do it? You have a method called Thread.Join to do so. So, if thread A starts thread B, a can call B.Join, which will cause A to pause until B is done.

Lets look at an example. Examine the following code.

static void Main(string[] args)
{
   
Thread firstThread = new Thread(FirstThread) ;
   
firstThread.Start() ;
 

   
Console.Read() ;
}
 

static
void FirstThread()
{
   
Thread.Sleep(10) ;
   
Thread secondThread = new Thread(SecondThread) ;
   
secondThread.Start() ;
   
Console.WriteLine("First thread finishing.") ;
}

static void SecondThread()
{
   
Thread.Sleep(100) ;
   
Console.WriteLine("Second thread finishing.") ;

}

So what am I doing above?

My main console application thread starts “firstThread”. firstThread should take about 10 milliseconds. But firstThread starts another thread – which takes about 100 milliseconds. Thus, in 99.9999% scenarios, you should see “First thread finishing” before “Second thread finishing”.

Indeed, if you run the above, that is exactly what will happen.

But, what if, some logic in firstThread depended upon secondThread finishing first? You could effectively pause (and optionally give a timeout) the execution of firstThread – until secondThread was done. Simply modify your code to the following.

static void FirstThread()
{
   
Thread.Sleep(10) ;
   
Thread secondThread = new Thread(SecondThread) ;
   
secondThread.Start() ;
   
secondThread.Join() ;
   
Console.WriteLine("First thread finishing.") ;
}

That’s it. Now, firstThread will wait for secondThread to finish before moving ahead. Now you will always see secondThread finishing before first thread prints “I’m finishing”.

This way, you can ensure an order between threads. This is one of the many tricks you can use, to ensure that your threads play well with each other.

Sound off but keep it civil:

Older comments..