How to raise only 1 Timer event in C#?
How do I get a timer event to fire one at a time. For example I have a timer that raises an event every 10 minutes. The event that is raised takes 10 or more minutes to finish executing. I would l开发者_JAVA百科ike the timer to reset AFTER the event has finished. In other words I do not want to raise more than 1 instance of the event at any one time.
Use System.Timers.Timer not the Threading one
Set AutoReset to false.
Then Start it again when you're done.
Usually what I do is have my event stop the timer when it's raised and then restart the timer when the event process completes:
private void timerHandler(object sender, TimerElapsedEventArgs e)
{
Timer timer = (Timer)sender;
timer.Stop();
RunProcess();
timer.Start();
}
public void RunProcess()
{
/* Do stuff that takes longer than my timer interval */
}
Now my timer will start again on completion of the process
It may be difficult to stop timers for efficiency or logic. The following code synchronizes skipping the events.
static readonly object key = new object();
void TimerHandler(object sender, TimerElapsedEventArgs e)
{
if(Monitor.TryEnter(key))
{
try
{
//do your stuff
}
finally
{
Montitor.Exit(key);
}
}
}
精彩评论