//Timer init.
var _timer = new System.Timers.Timer
{
AutoReset = true,
Enabled = true,
Interval = TimeSpan.FromSeconds(15).TotalMilliseconds //15 seconds interval
};
_timer.Elapsed += DoSomethingOnTimerElapsed;
//To be called on timer elapsed.
private void DoSomethingOnTimerElapsed(object source, ElapsedEventArgs e)
{
//Disable timer.
_timer.Enabled = false; //or _timer.Stop()
try
{
//does long running process
}
catch (Exception ex)
{
}
finally
{
if (_shouldEnableTimer) //set its default value to true.
_timer.Enabled = true; //or _timer.Start()
}
}
//somewhere in the code if you want to stop timer:
_timer.Enabled = _shouldEnableTimer = false;
//At any point, if you want to resume timer add this:
_timer.Enabled = _shouldEnableTimer = true;
为什么要这样做?
让我们假设,try 块中的代码需要更多的时间。因此,当您禁用计时器(_timer.Enabled = false or _timer.Stop())时,try 块中的代码仍然在执行的可能性很大。因此,在最终完成任务之后,如果没有标记(_shouldEnableTimer)检查,它将再次启用。因此,我通过添加额外的标志检查来防止您的问题。