Atomic timer callback design question
I want to call the timer callback just one time until it finishes the task. For example if the timer interval is five minutes and the task may be done within 2-20 minutes, if the previous task is not completed, new threads doesn't enter callback method.
Currently I do this by a volatile counter but it doesn't make sense to me. There should be a best practice. Sample code:
private volatile int _counter = 0;
private readonly object _syncLock = new object();
void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
lock(syncLock)
{
if (_counter > 0)
return;
else
开发者_StackOverflow社区 Interlocked.Increment(ref _counter);
}
// Method body
Interlocked.Decrement(ref _counter);
}
This one is simple enough actually. When you initialize the timer set the AutoReset
property to false.
_timer.AutoReset = false;
Then at the end of your event handler invoke this:
_timer.Start();
精彩评论