定时器在c#关闭后不会停止

本文关键字:定时器 | 更新日期: 2023-09-27 18:18:11

我创建定时器在我的形式,但我关闭形式后,定时器仍在工作。我尝试了不同的方法来停止这个计时器,但没有成功。

是什么问题?

private Timer timer100;
private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.timer100 = new System.Windows.Forms.Timer(this.components);
       this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
        this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed);
    }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        timer100.Stop();
    }
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        timer100.Dispose();
        timer100 = null;
    }

定时器在c#关闭后不会停止

我没有像jhmt在注释中提到的那样把InitializeComponent()放在MainForm的构造函数中