在我的应用程序中,我有一个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.
我已经放置了一个互锁装置,这样只有一个动作可以同时运行。但不幸的是,计时器两次发射它的事件,我不知道为什么。
答案 0 :(得分:1)
您可以在处理事件时始终禁用/启用计时器,即
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
}