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
Comments: