How can I force the system to wait creating a new thread if the previous is thread still running?

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 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;


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

    try {
        ... do some processing
    finally { // make sure to enable timer again

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.

Need Your Help

SQL Query to group dates by month

sql sql-server-2008

I have a database with 3 tables:

Matlab: a smart way to create a sparse matrix

matlab memory sparse-matrix

I have to create a matlab matrix that is much bigger that my phisical memory, and i want to take advantage of the sparsity.