Ensure Threads Finish Before Method Continues Thread Join

So I wrote a post a few weeks back using a different method for the same thing.  I used a counter to count how many threads I started, and then decremented them as they finished.  Once the counter was equal to zero, I let the method continue and finish.  However, I realized since then that using Thread.Join() (Thread Join) was a lot easier to use and manage to handle the same task.

So the set up is that we are spinning off a handful of threads, but we don’t want the method, such as Main() to continue until all threads are finished. So we start off by needing a list to add all the threads to once we start them.

protected List _threadList = new List();

Then in our methods where we create and start the threads we will add them to this list we just created.

//Create new thread
Thread logThread = new Thread(LogServiceCall);

//Start new thread
logThread.Start(logParams);

//Add thread to thread list
_threadList.Add(checkThread);

So after we have spun off all our threads; the next call in the method basically calls Thread.Join() on all threads within that list.  What Thread.Join() does is block the calling thread from terminating before all the other threads do.  So by doing this we can ensure that the main method won’t be able to finish until all the threads have since we cause the calling thread to hang.
This is the little snippet to call Thread.Join() on the thread list.

foreach (Thread thread in _threadList){
     thread.Join();
}

Once this completes, all the threads we started have to finish before the main calling thread can continue and terminate allowing the method to continue.  I find this to be a more compact and less heavy way to complete this task instead of using a counter.


StackOverflow Profile