1

Possible duplicate: What is the difference ManualResetEvent and AutoResetEvent in .net?

What is the difference between ManualResetEvent and AutoResetEvent ? (Example could be helpful).

Community
  • 1
  • 1
Udana
  • 13
  • 2
  • @ Fredrik .Please let the Jon complete his example.Then close it. – Udana Nov 28 '09 at 08:06
  • @Udana: I don't have the power of closing a question on my own; no worries. Also, I did note that the other question didn't have any code samples, so I would say the answers in this one does provide additional info. – Fredrik Mörk Nov 28 '09 at 08:36

1 Answers1

4

ManualResetEvent is like a gate in a field - once it's been opened, it lets people through until someone shuts it.

AutoResetEvent is like a turnstile in a train station - once you've put the ticket in, one person can go through, but only one.

Here's an example - 5 threads are all waiting for the same event, which is set once per second. With a manual reset event, all the threads "go through the gate" as soon as it's been set once. With an auto-reset event, only one goes at a time.

using System;
using System.Threading;

class Test
{
    static void Main()
    {
        // Change to AutoResetEvent to see different behaviour
        EventWaitHandle waitHandle = new ManualResetEvent(false);

        for (int i = 0; i < 5; i++)
        {
            int threadNumber = i;
            new Thread(() => WaitFor(threadNumber, waitHandle)).Start();
        }
        // Wait for all the threads to have started
        Thread.Sleep(500);

        // Now release the handle three times, waiting a
        // second between each time
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("Main thread setting");
            waitHandle.Set();
            Thread.Sleep(1000);
        }
    }

    static void WaitFor(int threadNumber, EventWaitHandle waitHandle)
    {
        Console.WriteLine("Thread {0} waiting", threadNumber);
        waitHandle.WaitOne();
        Console.WriteLine("Thread {0} finished", threadNumber);        
    }
}

Sample output for ManualResetEvent:

Thread 0 waiting
Thread 4 waiting
Thread 1 waiting
Thread 2 waiting
Thread 3 waiting
Main thread setting
Thread 2 finished
Thread 1 finished
Thread 0 finished
Thread 4 finished
Thread 3 finished
Main thread setting
Main thread setting

Sample output for AutoResetEvent:

Thread 0 waiting
Thread 1 waiting
Thread 2 waiting
Thread 3 waiting
Thread 4 waiting
Main thread setting
Thread 3 finished
Main thread setting
Thread 2 finished
Main thread setting
Thread 1 finished

(The program then just hangs, as there are two threads still waiting for the event to be set, and nothing is going to set it.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194