Reputation: 391
In my application I have a System.Timers.Timer which fires a second time a few milliseconds later.
Declaration of the timer:
mRecipeTimer = new System.Timers.Timer(30000);
mRecipeTimer.Start();
mRecipeTimer.Elapsed += new ElapsedEventHandler(mRecipeTimer_Elapsed);
Timer elapse event:
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;
}
}
And this is what I see in my logs:
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.
I allready placed an interlock so that only one action may run at the same time. But unfornately the timer fires its event twice and I don't know why.
Upvotes: 3
Views: 3663
Reputation: 38335
You can always disable/enable the timer while the event is being processed, i.e.,
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
}
Upvotes: 1