Search code examples
c#winformstimer

How to ignore first Interval on first run of System.Windows.Form.Timer?


I have a timer that repeats at 1 second intervals. Users can Start() or Stop() the timer.

System.Windows.Form.Timer timer = new();
timer.Interval = 1000;
timer.Tick += (sender, e) =>
{
  // Perform the action...
}

The problem is that in case of timer.Stop() it reacts immediately after pressing, but in case of timer.Start() it works after 1 second. This may feel strange to users.

So I solved it like this:

System.Windows.Form.Timer timer = new();
timer.Interval = 1;
timer.Tick += (sender, e) =>
{
  if (timer.Interval == 1)
  {
    timer.Interval = 1000;
  }

  // Perform the action...
}
private void StopButton_Click(object sender, EventArgs e)
{
  timer.Stop();
  timer.Interval = 1;
}

However, there is a problem that the timer's Interval must be continuously set to 1. One timer is fine, but having multiple complicates things.

Is there any other way?


Solution

  • Following comments from @jmcilhinney and @Zohar Peled, I solved it like this:

    System.Windows.Form.Timer timer = new();
    timer.Interval = 1000;
    timer.Tick += (sender, e) =>
    {
      StartOnFirstTimer();
    }
    
    private void StartOnFirstTimer()
    {
      // Perform the action...
    }
    
    private void StartButton_Click(object sender, EventArgs e)
    {
      StartOnFirstTimer();
      timer.Start();
    }
    

    It is extracted the part corresponding to the timer's Tick event into a method and call it before starting it.