Dot Net For All

ManualResetEvent with practical C# example

Hello, want to know about the practical use of ManualResetEvent in C# Threading scenarios? I will discuss in this article about the simplest signalling construct with a practical code example.

Before going Further you may find below article helpful:

What is ManualResetEvent in C#?

In our day to day programming with C# threading we come across the scenarios where we have to wait for signal of one thread to let the operation of some other thread to continue. This is simply known as signalling.

This is simplest signalling construct where calling WaitOne() blocks the current thread until other thread opens the signal be calling Set().

We can compare it with a very simple example of our day to day life. The railway crossing is a very good example of ManualResetEvent. While the signal(WaitOne) is red all the traffic(Waiting Thread) keeps waiting for the the train(blocking thread) to come. Once the train crosses the signal, it turns green and waiting traffic is allowed to go simultaneously unless and until signal is not red again.

In simple words there may be single or multiple threads waiting for the some other thread to signal for continuation.

Working With ManualResetEvent in C#

Creating an Instance – We can create an instance of this signalling construct by passing true or false in the constructor. If we have false as argument if means that the watching threads will wait unless it is set.

If we pass true as argument the thread(s) wont wait and will continue with their operation.

WaitOne – Method used by the waiting threads to wait for the signalling construct. Whatever comes after the waitone will be executed one the threads are signaled.

Set() – Waiting threads are signaled by some other thread to continue with their operation by using Set method of ManualResetEvent.

Reset() – The threads are put into waiting state once again by calling the Reset() method of the manualResetEvent.

C# Example

Please have a look at the below example to have a better understanding of this signalling construct.

In the below example I have two methods(Method1, Method2) which are working on two separate threads. And both of these methods are waiting for main thread to continue their operation.

The main thread signals the waiting threads every 5 seconds.

We can see the output in the console that each method is called exactly after 5 seconds.

        private static ManualResetEvent manualResetEvent = new ManualResetEvent(false);
        private static Stopwatch sw = new Stopwatch();
        static void Main(string[] args)
        {
            Method1();
            Method2();

            sw.Start();
            while (true)
            {
                Thread.Sleep(5000);
                manualResetEvent.Set();
            }
            
        }

        public async static Task Method1()
        {
            await new TaskFactory().StartNew(() =>
            {
                while (true)
                {
                    manualResetEvent.WaitOne();
                    Console.WriteLine(string.Format("Method 1 has done its operation in {0} seconds ",  sw.Elapsed.Seconds));
                    manualResetEvent.Reset();
                }
            });
        }

        public async static Task Method2()
        {
            await new TaskFactory().StartNew(() =>
            {
                while (true)
                {
                    manualResetEvent.WaitOne();
                    Console.WriteLine(string.Format("Method 2 has done its operation in {0} seconds " , sw.Elapsed.Seconds));
                    manualResetEvent.Reset();
                }
            });
        }

Have a look at the below figure to check for the output.

ManualResetEvent output

 

You can change the parameter of the Manual Reset Event constructor to true and notice the output at your end. You will find it interesting.

Conclusion:

In this article I have discussed how to wait for single or multiple thread using the simplest waiting construct with C# example. This can be very much helpful in multi threaded scenarios where we have to wait for the result of one operation to continue with other operations.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview