How to block a timer while processing the elapsed event?

后端 未结 5 1687
臣服心动
臣服心动 2021-02-13 09:00

I have a timer that needs to not process its elapsed event handler at the same time. But processing one Elapsed event may interfere with others. I implemented the bel

5条回答
  •  醉话见心
    2021-02-13 09:41

    You could set AutoReset to false, then explicitly reset the timer after you are done handling it. Of course, how you handle it really depends on how you expect the timer to operate. Doing it this way would allow your timer to drift away from the actual specified interval (as would stopping and restarting). Your mechanism would allow each interval to fire and be handled but it may result in a backlog of unhandled events that are handled now where near the expiration of the timer that cause the handler to be invoked.

    timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
    timer.Elapsed += Timer_OnElapsed;
    timer.AutoReset = false;
    timer.Start();
    
    
    public void Timer_OnElapsed(object sender, ElapsedEventArgs e)
    {
        if (!found)
        {
          found = LookForItWhichMightTakeALongTime();
        }
        timer.Start();
    }
    

提交回复
热议问题