【发布时间】:2019-10-21 12:02:22
【问题描述】:
对 C# 和计时器还很陌生,虽然我已经设法在 C# 中做了一些非常有趣的事情,但是我没有掌握 Timers 的窍门。
Form1.cs:
private int counter;
static System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
public void goTimer()
{
// Set Counter
counter = 60;
// If timer is already enabled, stop it.
if (timer1.Enabled)
{
timer1.Dispose();
//timer1.Stop() <- also tried
}
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start(); // Timer exists
txtCountdown.Text = counter.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if(counter == 0)
{
timer1.Stop();
}
txtCountdown.Text = counter.ToString();
}
所以,发生的事情是它似乎按预期工作,直到您开始从例如调用 goTimer();按下一个按钮,它就会加速 (int) counter 的速度,就像你按下它的次数一样......一段时间后内存会被吃光。
在这种情况下,用户将能够调用定时器函数,因为它会删除一些对象,清除一些数据并刷新会话,而且当定时器达到 0 时。
使用 Winforms,我确实没有在 Visual Studio 中添加计时器(它仅在 Form1.cs 中引用)。
如何终止所有计时器,然后在 (int) counter 处重新启动?
【问题讨论】:
-
定时器应该总是被处理掉,无论是否运行。 正确的地方是在表单的
Dispose方法中,而不是在启动计时器的方法中。 -
在任何情况下该方法都不安全 - 它每次调用它都会修改计时器,添加越来越多的事件处理程序,而它唯一应该做的就是调用
Start()