简体   繁体   中英

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 like 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);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM