AutoResetEvent and ManualResetEvent in C#

The section on this topic within the below MSDN article is excellent:

https://msdn.microsoft.com/en-us/library/ms173179.aspx

"Using a lock or monitor is useful for preventing the simultaneous execution of thread-sensitive blocks of code, but these constructs do not allow one thread to communicate an event to another

This requires synchronization events, which are objects that have one of two states, signaled and un-signaled, that can be used to activate and suspend threads

Threads can be suspended by being made to wait on a synchronization event that is unsignaled, and can be activated by changing the event state to signaled

If a thread attempts to wait on an event that is already signaled, then the thread continues to execute without delay.

There are two kinds of synchronization events: AutoResetEvent, and ManualResetEvent. They differ only in that AutoResetEvent changes from signaled to unsignaled automatically any time it activates a thread. Conversely, a ManualResetEvent allows any number of threads to be activated by its signaled state, and will only revert to an unsignaled state when its Reset method is called.
Threads can be made to wait on events by calling one of the wait methods, such as WaitOne, WaitAny, or WaitAll. WaitHandle.WaitOne causes the thread to wait until a single event becomes signaled, WaitHandle.WaitAny blocks a thread until one or more indicated events become signaled, andWaitHandle.WaitAll blocks the thread until all of the indicated events become signaled. An event becomes signaled when its Set method is called."

Let me translate all of this for you....

This is used in a scenario where we want to wait a thread on something done by another thread. In my case, I needed to make sure that a counter is zero and only then my thread should resume. If the counter gets to be greater than zero, then all my threads should pause.

To do this, I used a ManualResetEvent because I needed multiple threads to be paused and resumed. Also, I did not want to get unsignaled automatically just because one of my threads resumed. I wanted tight control when X happens pause, when Y happens resume, etc...

I initialized the event passing true to the constructor so that all my threads run at start-up.

When counter > 0 - Reset() - unsignal
When counter  = 0 - Set() - signal

On unsignal, my thread(s) pause

On signal, all of them resume.

This is much better than building this functionality yourself.

Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

Enable Visual Studio to use more than 2GB of memory