Thread Synchronization with CountdownEvent Construct

What is CountdownEvent and how to synchronize threads using CountdownEvent


Category: Multithreading Tags: C#


Introduction

        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.

Implementation

        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";
        t1.Start();
        t2.Start();
        eventCountdownWorker.Wait();
        Console.WriteLine("Both operations are completed");
        Console.ReadLine();
    }
    static void Print(int seconds)
    {
        Thread.Sleep(TimeSpan.FromSeconds(seconds));
        Console.WriteLine("{0} printing",Thread.CurrentThread.Name);
        eventCountdownWorker.Signal();
    }
}

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: 126
Questions: 9
Given Best Solutions: 8 *

Comments:

No Comments Yet

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

Existing User

Login via:

New User



x