表单未放置时计时器 [英] Timer not disposed when form is

查看:75
本文介绍了表单未放置时计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么创建表单的Windows $ .c时不丢弃Windows.Forms.Timer 的原因是。我有一个简单的表单:

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 释放了所处置对象拥有的所有对象。那是真的吗? 计时器是否有特定行为?

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()
{
    ....
}

这篇关于表单未放置时计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆