转:一个实例明白AutoResetEvent和ManulResetEvent的用法

这篇文章的原作者真是太有才了~~
转自:http://www.xhinker.com/2009/07/24/DotNet%E4%B8%80%E4%B8%AA%E5%AE%9E%E4%BE%8B%E6%98%8E%E7%99%BDAutoResetEvent%E5%92%8CManulResetEvent%E7%9A%84%E7%94%A8%E6%B3%95.aspx
 
public class WaitHandlerExample { 
                public static AutoResetEvent waitHandler; 
                public static ManualResetEvent manualWaitHandler; 
 
                public static void ThreadPoolMain() { 
                        waitHandler = new AutoResetEvent(false); 
                        manualWaitHandler = new ManualResetEvent(false); 
 
                        // Queue the task. 
                        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));             
                        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc2)); 
 
                        Console.WriteLine("Main thread does some work, then waiting...."); 
                        manualWaitHandler.WaitOne(); 
                        //waitHandler.Reset(); 
                        manualWaitHandler.WaitOne(); 
                        //waitHandler.Reset(); 
                        Console.WriteLine("Main thread exits."); 
                } 
 
                // This thread procedure performs the task. 
                public static void ThreadProc(Object stateInfo) { 
                        Thread.Sleep(1000); 
                        Console.WriteLine("Hello from the thread pool."); 
                        //waitHandler.Set();        // 
                        manualWaitHandler.Set();//过去了,但是没关,也就是说 信号还是开着的。 
                        //manualWaitHandler.Reset(); 
                } 
                public static void ThreadProc2(object stateInfo) { 
                        Thread.Sleep(100); 
                        Console.WriteLine("Hello from the thread Pool2"); 
                        //waitHandler.Set(); 
                        manualWaitHandler.Set();//过去了,但是没有关 
                } 
}
如果把 AutoResetEvent 比作 北京地铁的门闸,那么
 AutoResetEvent waitHandler=new AutoResetEvent(false);
可以看作,初始化闸机口为关闭状态,
 waitHandler.WaitOne(); 
可以看作刷卡
 waitHandler.Set()
表示通过,并且闸机自动关闭(AutoReset)为下次通过做准备。他的一个重大的好处,就是线程只能一个一个通过,保持了顺序又避免了死锁。
 
如果使用manualResetEvent 呢,那么在waitHandler.Set 之后,必须调用Reset()方法,为下面一位进去做好准备, 否则,就相当于无法再次刷卡。
 
体现在程序中就是,AutoResetEvent 可以WaitOne 很多次,可是ManualResetEvent 如果不Reset 下次就不能使用. 这就是他们的区别。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值