Thread Synchronization with CountdownEvent Construct

What is CountdownEvent and how to synchronize threads using CountdownEvent

Category: Multithreading Tags: C#


        CountdownEvent is used to wait until specified number of operations are completed. Its also signaling construct which signals once certain numbers of operations are completed.


        Have a look of code below:

class Program
    static CountdownEvent eventCountdownWorker = new CountdownEvent(2);
    static void Main(string[] args)
        Thread t1 = new Thread(() => Print(2));
        t1.Name = "t1";
        Thread t2 = new Thread(() => Print(4));
        t2.Name = "t2";
        Console.WriteLine("Both operations are completed");
    static void Print(int seconds)
        Console.WriteLine("{0} printing",Thread.CurrentThread.Name);

Above we created object of CountdownEvent where we specified number of operations are 2. and a method called Print which prints current thread's name and signals when it's completed. In main thread we created two threads and wait until two operations are completed using code line eventCountdownWorker.Wait once both threads are completed main thread's execution moves further, t1 waits for 2 seconds and t2 waits for 4 seconds before printing name so after 4 seconds both threads are completed and main threads can start execution. Output of above code:

t1 printing
t2 printing
Both operations are completed

Like 0 People
Last modified on 15 June 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 165
Questions: 16
Given Best Solutions: 16 *


No Comments Yet

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

Existing User

Login via:

New User