Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

c# - Timer not disposed when form is

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();
    }
}

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?

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?

EDIT

Or is it simply better to do:

private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
    timer.Dispose();
    this.Dispose();
}

?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;   
} 

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...