AutoResetEvent Reset immediately after Set

前端 未结 4 1129
花落未央
花落未央 2021-02-14 14:33

Consider the following pattern:

private AutoResetEvent signal = new AutoResetEvent(false);

private void Work()
{
    while (true)
    {
        Thread.Sleep(5000         


        
4条回答
  •  春和景丽
    2021-02-14 15:17

    Instead of using AutoResetEvent or ManualResetEvent, use this:

    public sealed class Signaller
    {
        public void PulseAll()
        {
            lock (_lock)
            {
                Monitor.PulseAll(_lock);
            }
        }
    
        public void Pulse()
        {
            lock (_lock)
            {
                Monitor.Pulse(_lock);
            }
        }
    
        public void Wait()
        {
            Wait(Timeout.Infinite);
        }
    
        public bool Wait(int timeoutMilliseconds)
        {
            lock (_lock)
            {
                return Monitor.Wait(_lock, timeoutMilliseconds);
            }
        }
    
        private readonly object _lock = new object();
    }
    

    Then change your code like so:

    private Signaller signal = new Signaller();
    
    private void Work()
    {
        while (true)
        {
            Thread.Sleep(5000);
            signal.Pulse(); // Or signal.PulseAll() to signal ALL waiting threads.
        }
    }
    
    public void WaitForNextEvent()
    {
        signal.Wait();
    }
    

提交回复
热议问题