does the timer thread wait till all the steps in the callback function are done or does the callback function get reinvoked in every period
c#, multithreading, timer
Solution
I assume you're using a `System.Threading.Timer`.
One way to do it is to create the timer as a one-shot, and then restart it after the thread has completed its task. That way you're certain that you won't have any overlap:
myTimer = new Timer(someMethod, null, 70000, Timeout.Infinite);
And in your callback:
void TimerCallback(object o)
{
// do stuff here
// then change the timer
myTimer.Change(70000, Timeout.Infinite);
}
Specifying `Timeout.Infinite` for the period disables periodic signaling, turning the timer into a one-shot.
Another way is to use a monitor:
object TimerLock = new object();
void TimerCallback(object o)
{
if (!Monitor.TryEnter(TimerLock))
{
// already in timer. Exit.
return;
}
// do stuff
// then release the lock
Monitor.Exit(TimerLock);
}
If you're wondering why I don't use a `try/finally` for the lock, see Eric Lippert's blog, Locks and exceptions do not mix.
The primary difference in these two approaches is that in the first the timer will fire 70 seconds after the previous callback execution finishes. In the second the timer will fire on a 70 second period, so the next callback might execute any time after the previous one finishes, from one second later to 70 seconds later.
For most things I've done, the first technique I showed seems to work better.
Problem
I have a timer thread function ``` SampleTimer = new Timer(SomeTask,0,70000) ``` call back function is as below ``` void SomeTask(object o) { //block using autoresetevent } ``` The issue is the SomeTask() callback method gets called every 70 secs even though all the operations in the callback method is still not done. How can I prevent the timer from calling the SomeTask() function before all the steps within it are completed