Question

I have a windows service that in the start method, creates a timer and triggers the timer to execute immediately. The timer is a long running task so the service on startup in services.msc gets detected as an error. It thought the timer below runs in a seperate thread and the service should start immediately ?

If i remove the line below it works fine but i want the service to trigger once the service is started.

_timer_Elapsed(null, null);

Removing this line makes the issue go away but i want this:

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
}
Était-ce utile?

La solution

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

This does not trigger the timer immediatly. All it does is execute the same procedure the timer is set to execute. Just in the thread of OnStart.

If you want the timer to trigger immediatly, set the interval to 1 or something small for the first round.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top