AutoResetEvent用法

  AutoResetEvent类,这个类有两个常用的方法,Set(),设置一个信号量,就是设置线程为终止,这样,WaitOne()方法后面的代码才会执行,然后会重置为非终止状态。

  只要知道只有先Set()信号,WaitOne()等到信号后才会继续执行。

  如果多个线程方法访问相同的AutoResetEvent对象,那么一次Set(),只能释放一个WaitOne(). 可以通过例子理解:http://msdn.microsoft.com/zh-cn/library/system.threading.autoresetevent.aspx

  下面是MSDN的例子:http://msdn.microsoft.com/zh-cn/library/system.threading.autoresetevent.autoresetevent.aspx

原文中说“程序逻辑可确保 ThreadProc 方法永远不会两次读取同一个值。 它并不确保 ThreadProc 方法将读取由 Main 写入的每一个值。 要确保这一点,则要求具有第二个 AutoResetEvent 锁定”; 下面是针对这句话的实现。

using System;
using System.Threading;

namespace AutoResetEvent_Examples
{
    class MyMainClass
    {
        //Initially not signaled.
        const int numIterations = 100;
        static AutoResetEvent myResetEvent = new AutoResetEvent(false);//需要先set()

        static AutoResetEvent event2 = new AutoResetEvent(true);//初始带有set()
        static int number;

        static void Main()
        {
            //Create and start the reader thread.
            Thread myReaderThread = new Thread(new ThreadStart(MyReadThreadProc));
            myReaderThread.Name = "ReaderThread";
            myReaderThread.Start();

            for (int i = 1; i <= numIterations; i++)
            {
                event2.WaitOne();
                Console.WriteLine("Writer thread writing value: {0}", i);
                number = i;

                //Signal that a value has been written.
                myResetEvent.Set();

                //Give the Reader thread an opportunity to act.
              //  Thread.Sleep(1);
            }

            //Terminate the reader thread.
            myReaderThread.Abort();
            Console.Read();
        }

        static void MyReadThreadProc()
        {
            while (true)
            {
                //The value will not be read until the writer has written
                // at least once since the last read.
                myResetEvent.WaitOne();
                Console.WriteLine("{0} reading value: {1}", Thread.CurrentThread.Name, number);

                event2.Set();
            }
        }
    }
}    
原文地址:https://www.cnblogs.com/wang7/p/2529159.html