.NET Waiting On Multiple Threads & Tasks With CountDownEvent

By Indranil Chatterjee

Waiting for spawned threads to finish is a common task in multithreaded programming. In earlier versions of .NET Framework, this was done using as many WaitHandle(s) as the spawned number of threads and then waitng on all of them. With CountDownEvent, we just need one wait handle (the CountDownevent). This FAQ gives a simple example to illustrate how.

If we had to spawn multiple threads and waitfor all of them to complete, in earlier versions of .NET Framework, we had to create that many wait handles (e.g. ManualResetEvent) and wait on all of them. With CountDownEvent in .NET Framework 4.0, this can be acheived using just one wait handle. A CountDownEvent can be initialized with a counter that indicates the number of threads to wait on. Individual threads (or tasks) can then signal the CountDownEvent. When this happens, it just decreaes the wait count by one and the event only gets signalled when the count reaches zero (i.e. when all the spawned threads/tasks complete). One can also increase the counter dynamically using AddCount or bring it back to the initial value by calling Reset.

Here is a sample code that illustrates its usage:

using System;
using System.Threading.Tasks;
using System.Threading;

namespace ParallelProgramming.TaskPrograms
{
class Program
{
//Initialize a CountDownevent with expected number of threads/tasks, 3 in this case
private static CountdownEvent _countDown = new CountdownEvent(3);

static void Main(string[] args)
{
//Start the individual tasks
Task.Factory.StartNew(() => DumpMessage("Task 1"));
Task.Factory.StartNew(() => DumpMessage("Task 2"));
Task.Factory.StartNew(() => DumpMessage("Task 3"));
//Wait on the countdown event
_countDown.Wait();
//the following code is reached only after all tasks complete
Console.WriteLine("All tasks are completed!");
}

private static void DumpMessage(string message)
{
//Simulating some work and wait time
Thread.Sleep(1000);
Console.WriteLine(message);
//Signals the countdown event, this just decrements the waiting count by one and event gets
//signalled only when the count reaches zero (i.e. when all tasks complete)
_countDown.Signal();
}
}
}

.NET Waiting On Multiple Threads & Tasks With CountDownEvent  (3635 Views)