An expired timer event fired twice in a C # command-line program

The expired timer event fires twice when the program starts. The sole purpose of the Expired event handler is the Primary Method. Is there something 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 car grill provided by @ fparadis2 recorded firing twice. The main problem was that my timer interval was set to 30 milliseconds instead of 30,000 milliseconds (30 seconds) so that the event would be double.

+6
source share
2 answers

If the timerInverval is small enough, it is possible that the Elapsed event will fire twice before you get a chance to stop the clock. You have to do

 Clock.AutoReset = false; 

to receive notifications only once every time the timer starts.

As stated in the documentation :

If Elapsed event processing takes longer than Interval, the event can be raised again in another ThreadPool thread. In this situation, the event handler must be reentrant.

+13
source

You can also consider this template.

+2
source

Source: https://habr.com/ru/post/891228/


All Articles