How to raise only 1 Timer event in C #?

How to get a timer event to fire one at a time. For example, I have a timer that triggers an event every 10 minutes. It takes 10 or more minutes to complete an event. I want the timer to be reset AFTER the event ends. In other words, I do not want to raise more than one instance of the event at any given time.

+3
source share
3 answers

Usually what I do is that my event stops the timer when it is raised, and then restarts the timer when the event process ends:

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 at the end of the process

+6
source

System.Timers.Timer Threading

AutoReset false.

, .

+14

It may be difficult to stop the timers for efficiency or logic. The following code synchronizes event skips.

static readonly object key = new object();

void TimerHandler(object sender, TimerElapsedEventArgs e)
{
  if(Monitor.TryEnter(key))
  {
    try
    {
      //do your stuff
    }
    finally
    {
      Montitor.Exit(key);
    }
  }
}
0
source

Source: https://habr.com/ru/post/1758073/


All Articles