System.Timers.Timer在几毫秒后第二次激发
本文关键字:几毫 第二次 Timer Timers System | 更新日期: 2023-09-27 18:21:57
在我的应用程序中,我有一个System.Timers.Timer,它会在几毫秒后再次触发。
计时器声明:
mRecipeTimer = new System.Timers.Timer(30000);
mRecipeTimer.Start();
mRecipeTimer.Elapsed += new ElapsedEventHandler(mRecipeTimer_Elapsed);
计时器流逝事件:
void mRecipeTimer_Elapsed(object sender, ElapsedEventArgs e)
{
int sync = Interlocked.CompareExchange(ref syncPoint, 1, 0);
if (sync == 0)
{
Thread.CurrentThread.Name = string.Format("timer, started at {0} ({1})", DateTime.Now, DateTime.Now.Millisecond);
Log.Info("Recipe timer elapsed.");
// some code
syncPoint = 0;
}
}
这就是我在日志中看到的:
2012-01-31 11:17:26,797 [timer, started at 1/31/2012 11:17:26 AM (797)] INFO - Recipe timer elapsed.
2012-01-31 11:17:27,875 [timer, started at 1/31/2012 11:17:27 AM (875)] INFO - Recipe timer elapsed.
2012-01-31 11:17:56,797 [timer, started at 1/31/2012 11:17:56 AM (797)] INFO - Recipe timer elapsed.
2012-01-31 11:17:57,875 [timer, started at 1/31/2012 11:17:57 AM (875)] INFO - Recipe timer elapsed.
我已经设置了一个互锁,这样在同一时间只能运行一个操作。但不幸的是,计时器触发了两次事件,我不知道为什么。
在处理事件时,您可以始终禁用/启用计时器,即
void mRecipeTimer_Elapsed(object sender, ElapsedEventArgs e)
{
mRecipeTimer.Enabled = false; //<---- disable
int sync = Interlocked.CompareExchange(ref syncPoint, 1, 0);
if (sync == 0)
{
Thread.CurrentThread.Name = string.Format("timer, started at {0} ({1})", DateTime.Now, DateTime.Now.Millisecond);
Log.Info("Recipe timer elapsed.");
// some code
syncPoint = 0;
}
mRecipeTimer.Enabled = true; //<---- enable
}