Joh*_*n M 6 c# command-line timer c#-4.0
程序启动时,我的计时器'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();
}
Run Code Online (Sandbox Code Playgroud)
更新:
@ fparadis2提供的AutoReset修复了两次射击.基本问题是我的计时器间隔设置为30毫秒而不是30000毫秒(30秒),因此事件是双击.
fpa*_*is2 13
如果timerInverval足够小,则有可能在您有机会停止时钟之前触发Elapsed事件两次.你应该做
Clock.AutoReset = false;
Run Code Online (Sandbox Code Playgroud)
每次启动计时器时仅通知一次.
如文档中所述:
如果Elapsed事件的处理持续时间超过Interval,则可能会在另一个ThreadPool线程上再次引发该事件.在这种情况下,事件处理程序应该是可重入的.