Posted by: Cirilo Meggiolaro | 10/31/2008

Tip of the day #17 – Joining threads

Today’s tip is very straightforward and easy to implement.

Sometimes when you are developing a multi-thread application you may want to make a piece of code to wait until some threads have finished their works and only after that to continue running the code.

Meanwhile the calling thread will be blocked, waiting until the last thread has finished its work.

How to…

The Join method is the way how we ask the calling thread to wait like in the following example:

myThread.Join();

Imagine that you have a code that starts 10 threads to perform a specific task and your code needs to wait the threads completion. Assuming that you have stored your threads references in an array, your code will be similar as the following:

foreach (Thread myThread in myThreads)
{
myThread.Join();
}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: