我创建了一个 Windows 服务,它时不时地运行一些任务,所以我使用了
System.Threading.Timer
。但在某些情况下,我注意到该函数停止被调用。
我通过写入日志文件进行检查,您可以检查程序可能在哪里停止。被调用函数的所有执行都已完成,但在某个时刻它停止被调用
这是我的代码:
namespace Service
{
public partial class Service: ServiceBase
{
protected override void OnStart(string[] args)
{
// do some stuff
log("Service Started"); // function that write in .txt file
// define delay and execution interval
Timer timer = new Timer(this.OnTimer, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(60));
}
public void OnTimer(object state)
{
log("Function fired");
// do something
log("Function closed");
}
protected override void OnStop()
{
log("Service stopped");
}
}
}
我需要调查或做什么才能确保该函数始终被调用?非常感谢!
namespace Service {
public partial class Service: ServiceBase {
Timer _timer;
protected override void OnStart(string[] args) {
// do some stuff
log("Service Started"); // function that write in .txt file
// define delay and execution interval
_timer = new Timer(OnTimer, null, 5000, 60000);
}
public void OnTimer(object state) {
Task.Run(() => {
log("Function fired");
// do something
log("Function closed");
});
}
protected override void OnStop() {
_timer.Dispose();
log("Service stopped");
}
}
}