c#4.0-在c#命令行程序中触发两次计时器运行事件
本文关键字:两次 计时器 事件 运行 命令行 程序 c#4 | 更新日期: 2023-09-27 18:00:03
程序启动时,我的计时器"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提供的"自动重置"两次修复了点火。基本问题是,我的计时器间隔被设置为30毫秒,而不是30000毫秒(30秒),因此事件是双重触发的。
如果timerInvalid足够小,则可能在您有机会停止时钟之前,Elapsed事件已触发两次。你应该做
Clock.AutoReset = false;
以便每次启动计时器时只收到一次通知。
如Timer Class文档中所述:
如果Elapsed事件的处理持续时间超过Interval,则可能会在另一个ThreadPool线程上再次引发该事件。在这种情况下,事件处理程序应该是可重入的。
您也可以考虑检查此模式。