C#中的计时器在数小时后停止触发事件
我有一个使用定时器的代码。它工作正常,但数小时后计时器停止引发已用事件:C#中的计时器在数小时后停止触发事件,c#,.net,C#,.net,我有一个使用定时器的代码。它工作正常,但数小时后计时器停止引发已用事件: using Timer = System.Timers.Timer; public void Start() { try { _timer = new Timer(Configuration.Configuration.MainLoopIntervalMs) {AutoReset = false}; _timer.Elapsed += Test; _timer
using Timer = System.Timers.Timer;
public void Start()
{
try
{
_timer = new Timer(Configuration.Configuration.MainLoopIntervalMs) {AutoReset = false};
_timer.Elapsed += Test;
_timer.Start();
}
catch (Exception e)
{
_logger.Error(e, "Exception ");
}
}
private void Test(object sender, ElapsedEventArgs eventArgs)
{
try
{
Console.WriteLine("Im doing here some more stuff");
}
catch(Exception e){ }
_timer.Stop();
_timer.Start();
}
它像预期的那样工作了几个小时,但随后
Test
方法停止执行,即使tohugh控制台应用程序仍在运行。原因可能是什么?有几点你应该检查一下
\u timer.Start()
->最后使用块
try catch
范围内\u timer.Stop()
是不必要的,因为AutoReset=false
意味着在触发后,计时器一旦停止,就会经过
\u timer.Disposed
,以监视它是否被代码中的其他组件释放(设置断点并等待它发生,然后查看调用堆栈):您是否确保垃圾收集器无法收集
\u timer
,如果//do some work
抛出异常,会发生什么情况?我认为System.Threading Timer而不是System.Timers Timer:)会发生这种情况,它位于try catch块中,没有异常空的catch块只会妨碍您检测代码中的问题。至少,记录一些东西。否则,请完全删除该try/catch。
using Timer = System.Timers.Timer;
public void Start()
{
try
{
_timer = new Timer(Configuration.Configuration.MainLoopIntervalMs) {AutoReset = false};
_timer.Elapsed += Test;
_timer.Start();
}
catch (Exception e)
{
_logger.Error(e, "Exception ");
}
}
private void Test(object sender, ElapsedEventArgs eventArgs)
{
// No code outside try-catch
try
{
_logger.Debug("Test - Start");
// Do all your work
Console.WriteLine("Im doing here some more stuff");
}
catch(Exception e)
{
_logger.Error(e, "Some usefull description")
}
finally
{
_timer.Start();
_logger.Debug("_timer restarted");
}
}