繁体   English   中英

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

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

程序启动时,我的计时器“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 秒),因此事件是双重触发的。

如果 timerInverval 足够小,则在您有机会停止时钟之前,Elapsed 事件可能会被触发两次。 你应该做

Clock.AutoReset = false;

以便每次启动计时器时仅收到一次通知。

计时器类文档中所述

如果 Elapsed 事件的处理持续时间超过 Interval,则可能会在另一个 ThreadPool 线程上再次引发该事件。 在这种情况下,事件处理程序应该是可重入的。

您也可以考虑检查此模式

暂无
暂无

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

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