联系
- 主要运用于线程通过发信号互相通信
- Set()方法将信号置为发送状态
- Reset方法将信号置为不发送状态
- WaitOne()等待信号的发送
- WaitAll()等待多个信号的发送
区别
在说区别之前先看看你能从下面的代码中能看出什么来
-
代码示例
using System; using System.Threading; namespace AutoResetEventTest class Program { static AutoResetEvent resetEvent = new AutoResetEvent(false); // static ManualResetEvent resetEvent = new ManualResetEvent(false); static void Main() { Thread thread = new Thread(new ThreadStart(Process)); thread.Start(); Thread.Sleep(3000); resetEvent.Set(); Console.ReadLine(); } static void Process() { while (true) { if (resetEvent.WaitOne()) { Console.WriteLine("received singal."); } } } } }
-
注释掉第9行,使用AutoResetEvent运行结果
-
注释掉第8行,使用ManualResetEvent运行结果
通过上面的例子,看出区别了吗?相信聪明的你一定看出了不同,对的,就是这样,下面笔者再来总结一下
-
AutoResetEvent一次只唤醒一个线程
AutoResetEvent.WaitOne()每次只允许一个线程进入,当某个线程得到信号后,AutoResetEvent会自动又将信号置为不发送状态,则其他调用WaitOne的线程只有继续等待
-
ManualResetEvent可以同时唤醒多个线程
当某个线程调用了ManualResetEvent.Set()方法后,其他调用WaitOne的线程获得信号得以继续执行,而ManualResetEvent不会自动将信号置为不发送,将会一直保持持有信号状态
-
AutoResetEvent.Set() = ManualResetEvent.Set()+ManualResetEvent.Reset()
Event.Set() = ManualResetEvent.Set()+ManualResetEvent.Reset()