0

我有一个 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
}
4

1 回答 1

1
_timer_Elapsed(null, null); // Get the timer to execute immediately

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

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

于 2014-04-13T13:36:46.500 回答