【问题标题】:Timer in seperate thread with long running task具有长时间运行任务的单独线程中的计时器
【发布时间】:2014-05-27 10:15:12
【问题描述】:

我有一个 Windows 服务,它在 start 方法中创建一个计时器并触发计时器立即执行。计时器是一项长时间运行的任务,因此 services.msc 中的启动服务会被检测为错误。它认为下面的计时器在单独的线程中运行,服务应该立即启动?

如果我删除下面的行,它可以正常工作,但我希望服务在服务启动后触发。

_timer_Elapsed(null, null);

删除此行会使问题消失,但我想要这个:

protected override void OnStart(string[] args)
{
    _timer = new System.Timers.Timer();
    _timer.AutoReset = false;
    _timer.Interval = (Convert.ToInt32(ConfigurationManager.AppSettings["CheckInterval"]));
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
    _timer.Enabled = true;
    _timer.Start(); // Get the timer to execute immediately
    _timer_Elapsed(null, null); // Get the timer to execute immediately
}

【问题讨论】:

    标签: c# timer system.timers.timer


    【解决方案1】:
    _timer_Elapsed(null, null); // Get the timer to execute immediately
    

    这不会立即触发计时器。它所做的只是执行定时器设置执行的相同过程。就在 OnStart 的线程中。

    如果您希望计时器立即触发,请将第一轮的间隔设置为 1 或较小的值。

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 2018-02-05
      • 1970-01-01
      • 2015-11-29
      • 2012-02-11
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      相关资源
      最近更新 更多