C#命令行程序中计时器已过期事件触发两次

8

当程序启动时,我的计时器“Elapsed”事件会触发两次。唯一分配“Elapsed”事件处理程序的位置是在“Main”方法中。我做错了什么吗?

//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();             
     }

更新:

@fparadis2 提供的 AutoReset 解决了两次触发的问题。根本原因是我的定时器间隔设置为 30 毫秒而不是 30000 毫秒(30 秒),导致事件双重触发。


可能是重复的问题:timer fire twice - user7116
2个回答

14

如果timerInverval足够小,可能会出现在您有机会停止时钟之前Elapsed事件被触发两次的情况。应该这样做:

Clock.AutoReset = false;
为了每次启动计时器时只收到一次通知。
如在计时器类文档中指定的:
如果处理 "Elapsed" 事件的时间超过 "Interval",则该事件可能会在另一个线程池线程上再次引发。在这种情况下,事件处理程序应为可重入的。

2

您还可以考虑查看这个模式,它与IT技术有关。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接