Multithreading: ManualResetEvent events

Published Tue, May 19 2009 10:17

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(() => {
                                        evt.WaitOne();
                                        Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
                                    }))
        .ToList();
    foreach (var thread in threads) {
        thread.Start();
    }
    Console.WriteLine("Fired threads");
    Thread.Sleep(200);
    evt.Set();
    Console.ReadLine();
}

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.

Filed under: ,

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover