VS 2015 C# - ElapsedEventHandler未在服务中触发

时间:2017-12-14 18:23:00

标签: c# visual-studio visual-studio-2015 service

我在VS 2015中开发了我的第一个C#服务,但我无法启动我的ElapsedEventHandler方法。我有以下代码:

using System;
using System.ServiceProcess;
using System.Timers;

namespace UpdateEnvironmentService
{
    public partial class Scheduler : ServiceBase
    {
        private Timer timer = null;
        public Scheduler()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer = new Timer();
            this.timer.Interval = Convert.ToDouble(1000); //timer intraval in milliseconds
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.UpdateData);
            timer.Enabled = true;
            Library.WriteLog("Data Updater Started ");
        }

        private void UpdateData(object sender, EventArgs e)
        {
            Library.WriteLog("Got to update Data ");
        }

        protected override void OnStop()
        {
            timer.Enabled = false;
            timer = null;
            Library.WriteLog("Data Updater Stopped ");
        }
    }
}

数据更新器启动这一行会打印到我的日志文件中,但我从未见过要更新数据,甚至数据更新器已停止。看来我的ElapsedEventHandler永远不会开火。任何人都知道为什么?

1 个答案:

答案 0 :(得分:0)

我会将您推荐给System.Timers.Timer类的documentation on MSDN

计时器的大多数示例和用法都倾向于避免直接设置Enabled,而是依赖于StartStop方法。

另一方面,我建议在Task年龄,你以不同的方式解决问题:

namespace UpdateEnvironmentService
{
    public partial class Scheduler : ServiceBase
    {
        private readonly CancellationTokenSource _tcs;
        public Scheduler()
        {
            InitializeComponent();
            _tcs = new CancellationTokenSource();
        }

        protected override void OnStart(string[] args)
        {
            Library.WriteLog("Data Updater Started ");
            Task.Factory.StartNew(Runner, _tcs.Token);
        }

        private async void Runner()
        {
            Library.WriteLog("In runner");
            var delay = TimeSpan.FromSeconds(1);
            while(!_tcs.IsCancellationRequested)
            {
                Library.WriteLog("Waiting...");
                await Task.Delay(delay, _tcs.Token);
                UpdateData();
            }
            Library.WriteLog("Cancellation requested; exiting runner");
        }

        private void UpdateData()
        {
            Library.WriteLog("Got to update Data ");
        }

        protected override void OnStop()
        {
            _tcs.Cancel();
            Library.WriteLog("Data Updater Stopped ");
        }
    }
}

这种方法不需要定时器,而是从任务中引入异步,允许线程池管理延迟;它还具有引入更好的取消控制的好处,这意味着它甚至可以在等待延迟时被取消!