How to raise only 1 Timer event in C#?

2019-07-02 06:21发布

问题:

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.

回答1:

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



回答2:

Use System.Timers.Timer not the Threading one

Set AutoReset to false.

Then Start it again when you're done.



回答3:

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


标签: c# events timer