Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer elapsed event firing twice in C# command line program

My timer 'Elapsed' event fires twice when the program is started. The only assignment of the 'Elapsed' event handler is in 'Main' method. Is there something that I'm doing wrong?

//class level clock
public static System.Timers.Timer Clock;

static void Main(string[] args)
    {
       Clock = new System.Timers.Timer();
       Clock.Elapsed += new ElapsedEventHandler(Clock_Elapsed);
       Clock.AutoReset = false;
       Clock.Interval = timerInterval; //this needs to be in milliseconds!
       Clock.Enabled = true;

       //run infinite loop until q is pressed
       while (Console.Read() != 'q')
       {}
    }

static void Clock_Elapsed(object sender, ElapsedEventArgs e)
    {
    Clock.Stop();
    //do some stuff
    Clock.Start();             
     }

UPDATE:

The AutoReset provided by @fparadis2 fixed the firing twice. The base issue was that my timer interval was set to 30 milliseconds instead of 30000 milliseconds(30 seconds) so that the event was double firing.

like image 890
John M Avatar asked Jun 23 '11 17:06

John M


People also ask

How do I stop a timer elapsed event?

timer. Start(); when you call the Start method timer starts ticking next moment and it starts firing the Elapsed event based on the interval set, and it keep ticking/firing Elapsed event for the interval you set at Step3 untill you execute the timer. Stop method.

How do you fire timer elapsed event immediately?

Just call the Timer_Tick method yourself. As pointed out by @Yahia, you could also use the System. Threading. Timer timer, which you can set to have an initial delay to 0.

What is timer elapsed in C#?

Elapsed event every two seconds (2000 milliseconds), sets up an event handler for the event, and starts the timer. The event handler displays the value of the ElapsedEventArgs. SignalTime property each time it is raised.


2 Answers

If timerInverval is small enough, it might be possible that the Elapsed event is fired twice before you get the chance to stop the clock. You should do

Clock.AutoReset = false;

in order to be notified only once each time you start the timer.

As specified in the Timer Class documentation:

If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant.

like image 176
fparadis2 Avatar answered Sep 22 '22 02:09

fparadis2


You may also consider checking this pattern.

like image 42
Jalal Said Avatar answered Sep 24 '22 02:09

Jalal Said