How to raise only 1 Timer event in C#?

穿精又带淫゛_ 提交于 2019-12-23 19:13:52

问题


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


来源:https://stackoverflow.com/questions/3409054/how-to-raise-only-1-timer-event-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!