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?
You are mistaken in the sense that no new thread will be created when the
Elapsedevent 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
Stopthe timer at the start of your event handler and toStartit again once it is finished. Like this:The other option is to set the
AutoResetproperty of the timer to false. This way the timer will only be raised once. Then you can callStartwhen you want it to start again. So the above code would change to include atimer.AutoReset = false;at the beginning and then you don’t need to callStopinside 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.