AutoResetEvent Reset immediately after Set

前端 未结 4 1105
花落未央
花落未央 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:13

    I would use TaskCompletionSources:

    private volatile TaskCompletionSource signal = new TaskCompletionSource();
    
    private void Work()
    {
        while (true)
        {
            Thread.Sleep(5000);
            var oldSignal = signal;
            signal = new TaskCompletionSource()
            //has a waiting thread definitely been signaled by now?
            oldSignal.SetResult(0);
        }
    }
    
    public void WaitForNextEvent()
    {
        signal.Task.Wait();
    }
    

    By the time that the code calls SetResult, no new code entering WaitForNextEvent can obtain the TaskCompletionSource that is being signalled.

提交回复
热议问题