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/archive/2012/05/31/2529159.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值