问题描述
我试图理解为什么 Windows.Forms.Timer
在创建它的 form
被释放时没有被释放.我有这个简单的形式:
I am trying to understand why a Windows.Forms.Timer
is not disposed when the form
that created it is. I have this simple form:
public partial class Form1 : Form {
private System.Windows.Forms.Timer timer;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(OnTimer);
timer.Enabled = true;
}
private void OnTimer(Object source, EventArgs e) {
Debug.WriteLine("OnTimer entered");
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
this.Dispose();
}
}
当我关闭它时,this.Dispose
被调用,但计时器触发事件继续被调用.我认为 Dispose
正在释放被处置对象拥有的所有对象.这是不真实的吗?Timer
是否有特定行为?
When I close it, this.Dispose
is called but the timer firing event continues to be called. I thought that the Dispose
was freeing all objects owned by the disposed object. Is that untrue? Does Timer
have a specific behavior?
现在,我发现处理计时器的方法是执行 timer.Tick -= OnTimer;
- 然后我在 Form1_FormClosed
事件中调用它.这是好的解决方案还是我应该这样做?
For now, I found that the way to dispose of the timer is to do timer.Tick -= OnTimer;
- I call it then in the Form1_FormClosed
event. Is it the good solution or should I do otherwise?
或者只是更好地做:
private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
timer.Dispose();
this.Dispose();
}
?
推荐答案
正如我在之前的评论中告诉你的,你应该尝试:
As I told you in my previous comment you should try:
private Form1_FormClosing(...)
{
timer.Stop();
timer.Tick -= new EventHandler(OnTimer);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
timer.Dispose();
timer = null;
}
这很好,因为您可以防止计时器再次循环(在 FormClosing 中)并且您可以检查其他部分(在此示例中不是因为您正在关闭表单,但作为示例)如果该对象(计时器)已在使用前删除.
所以在其他部分你可以做
This is good because you prevent timer to cycle again (in FormClosing) and you can check in other parts (non in this example because you're closing the form, but as example) if that object (timer) has been deleted before using it.
So in other parts you can do
if (timer != null) // Note: this is false if you just use timer.Dispose()
{
....
}
这篇关于表单时未处理计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!