[英]How to ignore first Interval on first run of System.Windows.Form.Timer?
I have a timer that repeats at 1 second intervals.我有一个以 1 秒为间隔重复的计时器。 Users can
Start()
or Stop()
the timer.用户可以
Start()
或Stop()
定时器。
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.问题是,在
timer.Stop()
的情况下,它会在按下后立即做出反应,但在timer.Start()
的情况下,它会在 1 秒后起作用。 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.但是有一个问题就是timer的Interval必须连续设置为1,一个timer还好,多个就麻烦了。
Is there any other way?还有别的办法吗?
Following comments from @jmcilhinney and @Zohar Peled , I solved it like this:根据@jmcilhinney和@Zohar Peled的评论,我这样解决了:
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.它将定时器的Tick事件对应的部分提取到一个方法中,并在启动之前调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.