手动重置事件基本问题

时间:2011-01-28 11:13:53

标签: c#

我对手动重置事件的等待方法感到困惑,请考虑下面的情况

static  object objLock = new object();

    static int counter = 5;

    static ManualResetEvent mEvent = new ManualResetEvent(false);

    static void Main(string[] args)
    {
        ///LeftShifting(10, 4);

       // RightShifting(3, 1);

       // Xoring(0001, 1001);

       // ExcahnageValuesWithXoring(10, 20);

       // ReverseBits(0);

        Thread.CurrentThread.Name = "Main Thread";

        for(int i=0;i<5;i++)
        {
            Thread t = new Thread(new ThreadStart(DoSomeLongWork));
            t.Name = i.ToString();
            t.Start();
        }

        Console.WriteLine("Current thread is " + Thread.CurrentThread.Name);

        mEvent.WaitOne();

        Console.WriteLine("Current thread is " + Thread.CurrentThread.Name);
        Console.WriteLine("Completed Long Running Process...");
        Console.ReadLine();
    }

    private static void DoSomeLongWork()
    {

        Console.WriteLine("Starting Long Running Process...On " + Thread.CurrentThread.Name);

        Thread.Sleep(5000);

        Interlocked.Decrement(ref counter);

        Console.WriteLine("Ending Long Running Process...On " + Thread.CurrentThread.Name);

        if (counter == 0)
            mEvent.Set();

    }

我的问题是,当我调用mEvent.Waitone()时,它是否会阻止“主线程”或正在执行的子线程之一。

2 个答案:

答案 0 :(得分:4)

它阻止主线程。这是可以阻止的唯一一个。你不能强迫另一个线程睡觉。主线程将等待另一个线程“设置”该事件。这与Monitor.Wait / Pulse非常相似。

答案 1 :(得分:1)

mEvent.WaitOne()将阻塞主线程,直到其中一个子线程调用mEvent.Set()