开发者

ASP.NET/C# Events difference

开发者 https://www.devze.com 2022-12-12 22:36 出处:网络
Possible duplicate: What is the difference ManualResetEvent and AutoResetEvent in .net? What is the difference between ManualResetEvent and AutoRese开发者_StackOverflow中文版tEvent ? (Example coul

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

What is the difference between ManualResetEvent and AutoRese开发者_StackOverflow中文版tEvent ? (Example could be helpful).


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消