Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause a Threading.timer to complete a function [duplicate]

Tags:

c#

.net

wpf

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?

like image 320
ar.gorgin Avatar asked Nov 07 '12 09:11

ar.gorgin


People also ask

How do you pause a timer in python?

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.

What is the difference between Thread and timer?

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.


2 Answers

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);
     }
   }
 }
like image 54
Ivan Leonenko Avatar answered Oct 03 '22 18:10

Ivan Leonenko


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.

like image 45
Adrian Thompson Phillips Avatar answered Oct 02 '22 18:10

Adrian Thompson Phillips