一个实例明白AutoResetEvent和 ManulResetEvent的用法
来源:互联网 发布:到期备案域名 编辑:程序博客网 时间:2024/05/21 12:43
先看一段代码:
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 下次就不能使用. 这就是他们的区别。
- 一个实例明白AutoResetEvent和 ManulResetEvent的用法
- 一个实例明白AutoResetEvent和 ManulResetEvent的用法
- 一个实例明白AutoResetEvent和 ManulResetEvent的用法
- 转:一个实例明白AutoResetEvent和ManulResetEvent的用法
- 一个实例明白AutoResetEvent和 ManulResetEvent的用法
- AutoResetEvent和ManualResetEvent用法
- 浅谈AutoResetEvent的用法
- 浅谈AutoResetEvent的用法
- 浅谈AutoResetEvent的用法
- 浅谈AutoResetEvent的用法
- 浅谈AutoResetEvent的用法
- 浅谈AutoResetEvent的用法
- 浅谈AutoResetEvent的用法(转)
- 浅谈AutoResetEvent的用法(转)
- 转:浅谈AutoResetEvent的用法
- AutoResetEvent用法
- AutoResetEvent WaitOne和Set使用实例
- ManualResetEvent和AutoResetEvent的区别
- ArcGIS实用制图技巧——如何制作“羽化”效果
- 关于mina的文件上传代码示例
- hdu 2837 Calculation
- My命名空间
- jackrabbit与spring2.5.6集成
- 一个实例明白AutoResetEvent和 ManulResetEvent的用法
- 个人的MATLAB练习
- 电脑开机出现disk error进不了系统,怎么办?
- 通向架构师的道路(第一天)之Apache整合Tomcat
- c/c++ 一些排序函数
- Storyboard入门
- 关于grep和egrep的一些整理
- 个数
- asp.net布局(一)表格布局