首页 > 解决方案 > C# - Winform Timer - 处理和清空计时器

问题描述

对 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

标签: c#winformstimer

解决方案


使用 start 和 stoptimer是正确的方法,但通常 dispose 变体也可以工作。

您的内存漏洞是由多重事件处理程序分配造成的,您需要将此方法移动到您的构造函数或其他一些初始化方法:

timer1.Tick += new EventHandler(timer1_Tick);

如果你真的想每次都创建一个新的定时器,你需要在之前释放事件处理程序:

timer1.Tick -= timer1_Tick;

推荐阅读