Possible Duplicate:
Synchronizing a timer to prevent overlap
I have a Threading.Timer
in my class.
System.Threading.Timer timer;
TimerCallback cb = new TimerCallback(ProcessTimerEvent);
timer = new Timer(cb, reset, 1000, Convert.ToInt64(this.Interval.TotalSeconds));
and defined a callback for it.
private void ProcessTimerEvent(object obj)
{
if(value)
MyFunction();
}
When run it, re-running callback before myfunction
to complete.
How to pause Threading.Timer
to complete myfunction
?
sleep() – Pause, Stop, Wait or Sleep your Python Code. Python's time module has a handy function called sleep(). Essentially, as the name implies, it pauses your Python program.
As we see above, Thread is the implementation that does the heavy lifting, and Timer is a helper that adds extra functionality (a delay at the front); Timer(0, func) wouldn't work if Thread didn't exist.
It is not necessary to stop timer, you could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately.
object lockObject = new object();
private void ProcessTimerEvent(object state)
{
if (Monitor.TryEnter(lockObject))
{
try
{
// Work here
}
finally
{
Monitor.Exit(lockObject);
}
}
}
You can disable a System.Threading.Timer
by changing the interval. You can do this by calling:
timer.Change(Timeout.Infinite, Timeout.Infinite);
You'll have to change the interval back once you have finished calling myfunction
if you want the timer to continue firing again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With