AutoResetEvent 类异步
官方描述:通知正在等待的线程已发生事件函数
命名空间:System.Threadingui
程序集:mscorlibspa
继承于:System.Threading.WaitHandle线程
AutoResetEvent从字面理解就是自动重置事件,那么它具体作什么的呢?举个例子:你们都坐过动车,要上车以前你们都要通过检票口的一道自动检票门,插入一张车票门就打开,人走过去以后门就自动关闭,保证一张车票过一我的,那么AutoResetEvent的做用就是这道自动检票门!blog
简单了解了AutoResetEvent的做用后,咱们来看看经常使用的函数:继承
示例:使用AutoResetEvent代替Thread.Sleep实现列队异步工做,来减小获取线程的获取的时间片事件
public class QueueWork<T> : IDisposable { private readonly Queue<T> _queue = new Queue<T>(); private readonly Thread _workerThread; private readonly object _locker = new object(); private readonly AutoResetEvent _waitEvent; private readonly Action<T> _workHandler; public QueueWork(Action<T> workHandler){ _workerThread = new Thread(Work); _waitEvent = new AutoResetEvent(false); _workHandler = workHandler; } public void Add(T data){ lock(_locker){ _queue.Enqueue(data); } _waitEvent.Set(); } private static void Work(){ while (!_isDisposed) { T data; lock(_locker){ if(_queue.Count>0){ data = _queue.Dequeue() } } if(data == null){ _waitEvent.WaitOne(); continue; } try{ workHandler(data); }catch{} } } private bool _isDisposed = false; public void Dispose(){ if(!_isDisposed){ _waitEvent.Set(); _workerThread.Join(); _waitEvent.Dispose(); } } }