Winform没有完全处置

时间:2016-04-25 16:01:14

标签: c# .net

我有一个表格菜单,不会完全处理。以下是完整的表单代码。它是更大系统的一部分,因此在首次打开Menu之前打开和关闭其他表单。

有一个表单计时器,每秒触发一次,并打印表单是否被处理。有一个按钮可以打开另一个表单,搜索并关闭菜单。搜索还有一个计时器,可以打印是否处理。

当菜单打开时,调试输出符合预期

*********** (in main menu): Disposed False
*********** (in main menu): Disposed False

当我点击时,我会看到菜单和搜索的计时器滴答

*********** (in main): Disposed True
*************** (in search) Disposed False

它显示菜单的第一个实例已处理,但显然计时器仍在运行。当我退出Search and Main打开时,现在有两个主计时器正在运行

*********** (in main): Disposed True
*********** (in main): Disposed False

我可以继续这样做(点击打开搜索并退出),运行的主计时器数量不断增加。我很困惑。这是Main

的代码
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;

namespace Gui
{
public partial class Menu : Form
{
    private System.Windows.Forms.Timer timer1;
    private Button button1;
    private IContainer components;

    public Menu()
    {
        InitializeComponent();
    }

    private void Menu_Load(object sender, EventArgs e)
    {
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Debug.Print("*********** (in main): Disposed {0}", IsDisposed);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var search = new Search();
        search.Show();
        Close();
    }
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.timer1 = new System.Windows.Forms.Timer(this.components);
        this.button1 = new System.Windows.Forms.Button();
        this.SuspendLayout();
        // 
        // timer1
        // 
        this.timer1.Enabled = true;
        this.timer1.Interval = 1000;
        this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
        // 
        // button1
        // 
        this.button1.Location = new System.Drawing.Point(11, 17);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(125, 32);
        this.button1.TabIndex = 0;
        this.button1.Text = "button1";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);
        // 
        // Menu
        // 
        this.ClientSize = new System.Drawing.Size(282, 253);
        this.Controls.Add(this.button1);
        this.Name = "Menu";
        this.Load += new System.EventHandler(this.Menu_Load);
        this.ResumeLayout(false);
    }
}
}

1 个答案:

答案 0 :(得分:3)

    this.timer1 = new System.Windows.Forms.Timer(this.components);

看起来您复制/粘贴了表单类的Designer.cs文件的内容。 InitializeComponent()方法当然是样板文件。但你做得不对,你忘了实际使用 this.components成员。这只存在一个原因,处理表单类使用的任何组件。像timer1一样。对于您在表单上放置的任何控件都是自动的,可以通过表单的控件成员找回它们,但组件需要额外的帮助。

所以不要只复制/粘贴InitializeComponent(),必须复制/粘贴Dispose()方法:

    protected override void Dispose(bool disposing) {
        if (disposing && (components != null)) {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

当您关闭表单时,计时器现在停止滴答。