2

I am using System.Timers in my program.

As we know each interval new thread is created to handle the OnTimedEvent.

I am looking for way to force the system to wait creating a new thread if the previous thread is still running.

My OnTimedEvent execute some method and I would like to wait until the method is finished

Any idea how to do that?

ChrisWue
  • 18,612
  • 4
  • 58
  • 83
MoShe
  • 6,197
  • 17
  • 51
  • 77
  • thread.Join() // Waits here until thread is finished. http://stackoverflow.com/questions/1584062/how-to-wait-for-thread-to-finish-with-net – MrFox Apr 07 '12 at 19:48
  • Do you have to use a timer? Can you not just loop the thread and, at the end, calculate how many ms to go until the next run and, if positive, sleep for that time? – Martin James Apr 07 '12 at 19:59
  • @Martin James- I use this application as windows service so I would like use timer and noe while(true) loop,@MrFox as I said I use timer... – MoShe Apr 07 '12 at 20:04

1 Answers1

2

You are mistaken in the sense that no new thread will be created when the Elapsed event is fired. The event will be raised on the the .NET threadpool, so an arbitrary thread will process it.

One way to do what you want is to Stop the timer at the start of your event handler and to Start it again once it is finished. Like this:

var timer = new System.Timers.Timer(1000);
timer.Elapsed += HandleTimerElapsed;
timer.Start();

...

private void HandleTimerElapsed(object s, ElapsedEventArgs e)
{
    var t = (System.Timers.Timer)s;
    t.Stop();

    try {
        ... do some processing
    }
    finally { // make sure to enable timer again
        t.Start();
    } 
}

The other option is to set the AutoReset property of the timer to false. This way the timer will only be raised once. Then you can call Start when you want it to start again. So the above code would change to include a timer.AutoReset = false; at the beginning and then you don't need to call Stop inside the handler. This is a bit safer as the above method probably has a race condition in the sense that if the system is under load your handler might not be guaranteed to execute before the timer elapses again.

ChrisWue
  • 18,612
  • 4
  • 58
  • 83