c# - 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
?
解决方案
使用 start 和 stoptimer
是正确的方法,但通常 dispose 变体也可以工作。
您的内存漏洞是由多重事件处理程序分配造成的,您需要将此方法移动到您的构造函数或其他一些初始化方法:
timer1.Tick += new EventHandler(timer1_Tick);
如果你真的想每次都创建一个新的定时器,你需要在之前释放事件处理程序:
timer1.Tick -= timer1_Tick;
推荐阅读
- javascript - 为什么这种 IIFE 模式适用于闭包,而常规函数调用却不行?
- c++ - 从 Qt 中的 c++ 文件快速填充组合框项目
- asp.net-mvc - 在 WEB API 项目中安装 Kendo.MVC 时出现问题
- swift - swift 是否可以使用字符串名称和键路径表达式设置属性?
- vb.net - 我的编辑按钮和删除按钮是冲突的
- javascript - 赛普拉斯 - 将其安装在空项目上
- django - 如何使 loacalhost django 与在 docker 容器中工作的 posgtres 交互?
- c# - C# ActiveX VLC 插件 - 音频问题
- mysql - #1052 - 字段列表中的列“状态”不明确 MySQL
- syslog - Graylog 不显示来自客户端的日志或消息