我开发了使用 System.Threading.Timer 的 Windows 服务。计时器每 x 分钟启动一次,它工作正常(计时器在方法结束时更新)。但是,如果尝试阻止服务出现错误,尽管我正在更新计时器并告诉他何时重新开始,但为什么会发生这种情况?这是代码:
System.Threading.Timer serviceTimer;
protected override void OnStart(string[] args)
{
TimeSpan diff;
diff = nextRun - now;
TimerCallback timerDelegate =
new TimerCallback(MyTimerCallback);
serviceTimer = new System.Threading.Timer(timerDelegate, null,
diff, new TimeSpan(-1));
}
public void MyTimerCallback(object something)
{
try
{
//possible error that happened
}
catch(Exception)
{
}
finally
{
//diff is a new variable telling timer when to start again
serviceTimer.Change(diff, new TimeSpan(-1));
}
}
如果出现错误,我错过了为什么服务会停止?