您不需要任何锁,您应该从计时器委托中重新安排下一个计时器执行。这应该确保 100% 没有重叠。
在计时器的事件处理程序调用结束时,计时器timer.Change(nextRunInMilliseconds, Timeout.Infinite)
只会在 之后触发一次nextRunInMilliseconds
。
例子:
//Object that holds timer state, and possible additional data
private class TimerState
{
public Timer Timer { get; set; }
public bool Stop { get; set; }
}
public void Run()
{
var timerState = new TimerState();
//Create the timer but don't start it
timerState.Timer = new Timer(OnTimer, timerState, Timeout.Infinite, Timeout.Infinite);
//Start the timer
timerState.Timer.Change(1000, Timeout.Infinite);
}
public void OnTimer(object state)
{
var timerState = (TimerState) state;
try
{
//Do work
}
finally
{
//Reschedule timer
if (!timerState.Stop)
timerState.Timer.Change(1000, Timeout.Infinite);
}
}