简体   繁体   English

在 C# 命令行程序中定时器已用事件触发两次

[英]Timer elapsed event firing twice in C# command line program

My timer 'Elapsed' event fires twice when the program is started.程序启动时,我的计时器“Elapsed”事件会触发两次。 The only assignment of the 'Elapsed' event handler is in 'Main' method. 'Elapsed' 事件处理程序的唯一分配是在 'Main' 方法中。 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. @fparadis2 提供的 AutoReset 修复了两次触发。 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.基本问题是我的计时器间隔设置为 30 毫秒而不是 30000 毫秒(30 秒),因此事件是双重触发的。

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.如果 timerInverval 足够小,则在您有机会停止时钟之前,Elapsed 事件可能会被触发两次。 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.如果 Elapsed 事件的处理持续时间超过 Interval,则可能会在另一个 ThreadPool 线程上再次引发该事件。 In this situation, the event handler should be reentrant.在这种情况下,事件处理程序应该是可重入的。

您也可以考虑检查此模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM