Hi all. Today let us learn about CountdownEvent class in C#.
What is a CountdownEvent?
Note. Here is the definition from MS docs
System.Threading.CountdownEvent is a synchronization primitive that unblocks its waiting threads after it has been signaled a certain number of times.
Definition from the internet
A much more simpler definition from the internet
The CountdownEvent class in C# is a part of the System.Threading namespace and is used for managing synchronization between multiple threads. It is designed to coordinate a specific number of signals before allowing waiting threads to proceed.
CountdownEvent in Action
There are three primary steps in implementing the CountdownEvent class.
Step 1. You need to initialize the CoutdownEvent class to a target count.
CountdownEvent countdownEvent = new CountdownEvent(3);
Step 2. Write the Signal() event as per your logic.
countdownEvent.Signal();
Step 3. Finally call the Wait() method to wait for all signals to be called which blocks the current thread.
countdownEvent.Wait();
Note. A simple program to see the class in action.
The Program
namespace Practice
{
public class Program
{
static void Main(string[] args)
{
int delayTimeInSeconds = 0;
Console.WriteLine($"Program started at: {DateTime.Now.ToString("hh:mm ss tt")}");
CountdownEvent countdownEvent = new CountdownEvent(3);
for (int i = 1; i <= 3; i++)
{
_ = Task.Run(async () =>
{
delayTimeInSeconds += 2;
await Task.Delay(TimeSpan.FromSeconds(delayTimeInSeconds));
Console.WriteLine($"Task completed at {DateTime.Now.ToString("hh:mm ss tt")}");
}).ContinueWith(t =>
{
countdownEvent.Signal();
});
}
Console.WriteLine("Initialized all tasks. Waiting for their completion");
countdownEvent.Wait();
Console.WriteLine("Program Completed");
}
}
}
Program explanation
A simple program where you initalize three tasks that complete after 'n' seconds. At the end of each task, the countdown event is signaled. At the end of the program we have written the countdown Wait() method which waits till all the three countdown events are signaled or simply till all the three tasks are completed.
Program Output
Thus the CountdownEvent class in C#.
Hope you found it useful. Thank you all.