System.Threading.Timer 调用的函数出现问题

问题描述 投票:0回答:1

我创建了一个 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");
        }
    }
}

我需要调查或做什么才能确保该函数始终被调用?非常感谢!

c# timer windows-services
1个回答
0
投票
  1. 检查每个“功能已触发”的“功能已关闭”。
  2. 检查“日志”不要损坏。
  3. 在 OnTimer 中运行任务,将执行的代码与计时器隔离。
  4. 将计时器设置为停止状态。
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");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.