Thread Synchronization with AutoResetEvent Construct

What is AutoResetEvent and how to synchronize threads using AutoResetEvent


Category: Multithreading Tags: C#


Introduction

        Using AutoResetEvent we can send notification from one thread to other. AutoResetEvent notifies that an event has occurred.

Implementation

        Observe code below to understand

class Program
{
    static AutoResetEvent eventWorker = new AutoResetEvent(false);
    static AutoResetEvent eventMain = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        Thread t = new Thread(() => AutoResetFun(3000));
        t.Start();
        Console.WriteLine("Letting worker thread run");
        eventMain.WaitOne();
        Console.WriteLine("Main thread completed");
        eventWorker.Set();
        eventMain.WaitOne();
        Console.ReadLine();
    }
    static void AutoResetFun(int miliseconds)
    {
        Console.WriteLine("Started worker thread");
        Thread.Sleep(miliseconds);
        Console.WriteLine("Waiting for main thread to complete");
        eventMain.Set();
        eventWorker.WaitOne();
        Console.WriteLine("Worker thread completed");
        eventMain.Set();
    }
}

Above we created two AutoResetEvent objects eventWorker and eventMain, one for main thread and one for worker thread and set these initially in non-signaled state(by passing false in constructor) then in main thread we created one worker thread t. The WaitOne method will block current execution and will be blocked until program calls Set method to get back AutoResetEvent in signaled state. When eventMain.WaitOne is executed main thread gets blocked but thread t keeps running, and when thread t executes eventMain.Set then again main thread resumes execution and worker thread gets blocked by execution of eventWorker.WaitOne and so on. Above program prints output:


Letting worker thread run
Started worker thread
Waiting for main thread to complete
Main thread completed
Worker thread completed



We initialized both events in initial state false which is non-signaled means when we call WaitOne thread will wait until Set method is executed once Set method is executed AutoResetEvent goes in signaled state and thread gets unblocked once thread is unblocked AutoResetEvent automatically goes back to non-signaled state. If we set events initially to true means state is already in signaled then WaitOne will let execution pass through as soon as it gets encountered and state will become non-signaled.


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