Reputation: 951
I'm working on a Windows Service with a timer to schedule a job each interval of time. It seems that the timer elapsed event is fired more than one time.
Here a code sample:
private static System.Timers.Timer _timer = new System.Timers.Timer();
protected override void OnStart(string[] args)
{
_timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
_timer.Interval = 1000;
_timer.Enabled = true;
_timer.Start();
}
private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
_timer.Enabled = false;
_timer.Stop();
//Do the job
_timer.Enabled = true;
_timer.Start();
}
Can you help me? Thank you
Upvotes: 2
Views: 5141
Reputation: 32571
The signal to raise the Elapsed event is always queued for execution on a ThreadPool thread, so the event-handling method might run on one thread at the same time that a call to the Stop method runs on another thread. This might result in the Elapsed event being raised after the Stop method is called. The code example in the next section shows one way to work around this race condition.
Quoted from: Timer.Stop Method. Please see the code sample on the page.
Upvotes: 1