我正在开发一个基本上运行以下代码的Windows服务:
public class ServiceController
{
private FundsEngine _fundsEngine;
protected override void OnStart(string[] args)
{
var logsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
if (Directory.Exists(logsPath) == false)
{
Directory.CreateDirectory(logsPath);
}
_fundsEngine = new FundsEngine();
_fundsEngine.Start();
}
}
该服务可以启动“Engines”,它们只是使用Timers在指定时间间隔内执行代码的类。
以下类是引擎的示例,该引擎使用System.Threading.Timer
每5秒调用一次回调OnTick()
。
public class FundsEngine
{
private System.Threading.Timer _timer;
private static Logger _logger = LogManager.GetCurrentClassLogger();
public void Start()
{
_logger.Trace("Begin Start");
try
{
// details omitted
_timer = new Timer(OnTick);
_timer.Change(5000, Timeout.Infinite);
}
catch (Exception exception)
{
_logger.ErrorException("Error in Start.", exception);
}
finally
{
_logger.Trace("End Start");
}
}
private void OnTick(object state)
{
_logger.Trace("Begin Tick");
try
{
// do stuff
_timer.Change(5000, Timeout.Infinite);
}
catch (Exception exception)
{
_logger.ErrorException("Error in Tick. ", exception);
}
finally
{
_logger.Trace("End Tick");
}
}
}
如下面的日志所示,Timer按预期工作,每5秒调用一次OnTick()
方法。
2013-05-14 16:27:01.2261|TRACE|Begin Start
2013-05-14 16:27:03.8514|TRACE|End Start
2013-05-14 16:27:08.8569|TRACE|Begin Tick
2013-05-14 16:27:08.8709|TRACE|End Tick
2013-05-14 16:27:13.8734|TRACE|Begin Tick
2013-05-14 16:27:13.8734|TRACE|End Tick
2013-05-14 16:27:18.8809|TRACE|Begin Tick
2013-05-14 16:27:18.8809|TRACE|End Tick
2013-05-14 16:27:23.8894|TRACE|Begin Tick
2013-05-14 16:27:23.8894|TRACE|End Tick
2013-05-14 16:27:28.8969|TRACE|Begin Tick
2013-05-14 16:27:28.8969|TRACE|End Tick
2013-05-14 16:27:33.9044|TRACE|Begin Tick
2013-05-14 16:27:33.9044|TRACE|End Tick
如果在OnTick()
方法中捕获到异常,我的期望是它将被记录,并且服务将继续运行,以便再次调用OnTick()
方法5秒。但是,情况并非如此,因为在处理Exception之后永远不会再次调用回调。这是为什么?
2013-05-14 16:29:03.8574|TRACE|Begin Start
2013-05-14 16:29:03.8574|TRACE|End Start
2013-05-14 16:29:08.8709|TRACE|Begin Tick
2013-05-14 16:29:09.9750|ERROR|Error in Tick. System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it 127.0.0.1:22
2013-05-14 16:29:09.9750|TRACE|End Tick
答案 0 :(得分:1)
答案 1 :(得分:1)
_timer.Change(5000, Timeout.Infinite);
您没有创建一个句点计时器,为期间参数传递无限。计时器只会调用一次OnTick()。然而,代码非常不完整,唯一可行的方法是它再次调用Change()来为计时器充电。
异常绕过此Change()调用的几率很高。如果你想保持它,那么这个Change()调用属于 finally 块。虽然这样做实际上并不是一个好主意,但是过程状态被破坏并且它将再次崩溃的非零赔率。一遍又一遍。你至少应该对此采取对策,并计算连续崩溃的次数,当它只是反复轰炸时放弃。