Question

I am currently using this 'timer code' in a windows service:

var autoEvent = new AutoResetEvent(false);
Timer = new Timer(DoWork, autoEvent, 0, TimeInMilliSeconds);

I am just wondering whether it would be possible to prevent the invocation of DoWork, if DoWork has not finished yet? In other words, if TimeInMilliSeconds is shorter than the time it takes to execute DoWork?

Was it helpful?

Solution

If I understand correctly then you can prevent the automatic callback and change the timer once when you need.

Timer = new Timer(DoWork, autoEvent, 0, Timeout.Infinite);//Prevent periodic timer

void DoWork(object state)
{
    //Do work and then set timer again
    timer.Change(TimeInMilliSeconds, Timeout.Infinite);
}

Don't forget to add try/finally block, if you don't do your timer will not be called again in case of exception.

OTHER TIPS

You could avoid using a timer altogether. In my program, I set the stop and pause events in the OnStop and OnPause methods. They are cleared in the OnStart and OnContinue methods. In this example I wait 30 seconds between trips through the loop.

 WaitHandle[] waitFor = new WaitHandle[]{stopEvent, pauseEvent};
 int trigger = -1;
 bool keepGoing = true;
 while(keepGoing)
 {
     trigger = WaitHandle.WaitAny(waitFor, TimeSpan.FromSeconds(30));
     switch (trigger) {
         case WaitHandle.WaitTimeout:
            The main body of the loop goes here
            break;
         case 0: // stop
             keepGoing = false;
             break;
         case 1: // pause
             System.Diagnostics.Debug.Write("Paused - ");
             System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString());
             break;
     }

Edit As noted in another poster's comment, this is required to be in a thread separate from your main service. Otherwise you will never process the stop, pause or resume events.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top