开发者

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开发者_StackOverflow社区();             
     }

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.


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.


You may also consider checking this pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜