我也多次遇到类似的问题。
//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()
var markers = new Dictionary<string, ConversationItem>();
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(_timer.Enabled = false or _timer.Stop())
时,try 块内的代码很有可能仍在执行。因此,在finally任务完成后,如果没有flag( _shouldEnableTimer
)检查,则再次启用。因此,我通过添加额外的标志检查来防止您的问题。
为了更清楚,请仔细阅读代码和添加的注释。希望这可以帮助。