May 19

Multithreading: ManualResetEvent events

Posted in C# Multithreading      Comments Off on Multithreading: ManualResetEvent events

Yesterday we’ve taken a peek at the AutoResetEvent. Today, we’re going to keep looking at kernel objects and we’ll see how we can use the ManualResetEvent for synchronization purposes. I guess that the easiest way to show them doing some work is by going straight to the code.

Yesterday we’ve taken a look at a really dumb sample that showed the behavior of the AutoResetEvent class. Today, we’re porting (sort of) that sample so that it uses the ManualResetEvent class:

using (var evt = new ManualResetEvent(false)) {   
    var threads = Enumerable.Range(0, 2)
        .Select(i => new Thread(() => {
    foreach (var thread in threads) {
    Console.WriteLine("Fired threads");

As you can see, we start by creating a new ManualResetEvent in the non signaled state. Then, we create and start two threads which block until the event is set. As you can see, we don’t need to set the event in the secondary threads (like we did in yesterday’s sample). That happens because the event isn’t automatically reset after it has been set. If we needed that, then we would need to call the Reset method. Unfortunately, I’m out of time to present a more interesting sample, but I’ll return to the topic in a future post. Keep tuned.