Join Threads of Thread Pool

How to join threads of thread pool using CountdownEvent


Category: Multithreading Tags: C#


Introductions

        Usually we use Thread.Join() method on all created threads to wait until all threads are completed. In this article I will show you easiest way to join threads if threads are on thread pool.

Implementation

        First we have to create a method which will be executed on thread:

static void ThreadPoolJoin(int seconds, CountdownEvent evt)
{
    Thread.Sleep(TimeSpan.FromSeconds(seconds));
    Console.WriteLine("Hi from Thread:{0}", Thread.CurrentThread.ManagedThreadId);
    evt.Signal();
}

Above method we are printing thread id and signaling CountdownEvent. Actually we are using CountdownEvent which I described in my previous article. Here we are passing CountdownEvent as parameter and signaling it once operation is completed. In main thread:

static void Main(string[] args)
{
    int threadCount = 5;
    Console.WriteLine("Starting Threads");

using (CountdownEvent counter = new CountdownEvent(threadCount)) { for (int i = 0; i < threadCount; i++) { int sleepTime = i; ThreadPool.QueueUserWorkItem(_=> ThreadPoolJoin(sleepTime, counter)); } counter.Wait(); } Console.WriteLine("All threads finished execution"); Console.ReadLine(); }

Above code we created object of CountdownEvent and set threadCount as five, we posted five operations on thread pool with sleepTime in increasing order. Once all operations are posted we used counter.Wait() to wait which actually will work as Join and wait until all threads are completed execution. Output will be:

Starting Threads
Hi from Thread:11
Hi from Thread:12
Hi from Thread:11
Hi from Thread:13
Hi from Thread:14
All threads finished execution


Like 0 People
Last modified on 10 October 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 129
Questions: 9
Given Best Solutions: 9 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x