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?

Answers


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.


Need Your Help

Should we use _.foreach() or better the native for of loop in TypeScript

performance typescript foreach lodash

I just started to work in a new project working with TypeScript. I'm comming from another project that also worked with TypeScript. Since the native for of loop in TypeScript is avaible we decided ...

Using iPhone audio files in own app - copy the audio file - is that possible?

iphone audio mpmediapickercontroller mpmediaitem

I like the user to pick an audio file from the available list of audio and copy it into my own app. In the retrieved items of userMediaItemCollection in the Apple sample code "AddMusic" there is the