简体   繁体   中英

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?

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.

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