【发布时间】:2020-04-27 09:55:32
【问题描述】:
当程序启动时,我的计时器“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 的可能重复项
标签: c# c#-4.0 command-line timer