Synchronizing a Timers.Timer elapsed method when stopping

后端 未结 5 1510
情书的邮戳
情书的邮戳 2020-12-19 09:18

With reference to this quote from MSDN about the System.Timers.Timer:

The Timer.Elapsed event is raised on a ThreadPool thread, so the event-handl

5条回答
  •  天涯浪人
    2020-12-19 09:47

    Here is a very simple way to prevent this race condition from occurring:

    private object _lock = new object();
    private Timer _timer; // init somewhere else
    
    public void StopTheTimer()
    {
        lock (_lock) 
        {
            _timer.Stop();
        }
    }
    
    void elapsed(...)
    {
        lock (_lock)
        {
            if (_timer.Enabled) // prevent event after Stop() is called
            {
                // do whatever you do in the timer event
            }
        }
    }
    

提交回复
热议问题