简体   繁体   English

如何处理对象处置异常是C#中未处理的异常?

[英]How to handle object disposed exception was unhandled Exception in c#?

我在C#Windows应用程序中工作。我有两个窗口,分别是Form1和Form2。我正在通过单击Form1中的按钮来调用Form2,但是我在Form1的构造函数中为Form2创建了对象。如果我第一次单击按钮,则Form2出现了成功之后,我通过单击默认的关闭按钮关闭了form2,然后再次单击该按钮,现在我得到对象处置异常是未处理的异常。如何避免这种情况?

Don't handle the exception, fix the bug in your code. 不要处理异常,请修复代码中的错误。 The form instance is dead after the form is closed, you cannot show it again. 关闭表单后,表单实例已失效,无法再次显示。 Either write it like this: 可以这样写:

    private void button1_Click(object sender, EventArgs e) {
        var frm = new Form2();
        frm.Show(this);
    }

Or if you want only one instance of the form to be ever visible: 或者,如果您只希望表单的一个实例可见:

    Form2 theForm;

    private void button1_Click(object sender, EventArgs e) {
        if (theForm != null) {
            theForm.WindowState = FormWindowState.Normal;
            theForm.BringToFront();
        }
        else {
            theForm = new Form2();
            theForm.FormClosed += delegate { theForm = null; };
            theForm.Show(this);
        }
    }

You are keeping a reference to the object (window here) but you are closing it. 您正在保留对该对象的引用(此处的窗口),但您正在关闭它。 Object is disposed but is not garbage collected. 对象已处置但未进行垃圾收集。 Your reference here is invalid now as the object has lost its usable state. 由于对象已失去其可用状态,因此此处的引用现在无效。

You need to hide the form instead of close if you need to re-use it. 如果您需要重新使用它,则需要隐藏它而不是关闭它。 Or create a new instance to load it again. 或创建一个新实例以再次加载它。

You can use events in order to let form1 know when form2 has been closed and clear its reference to it. 您可以使用事件,以便在关闭form2时通知form1并清除对其的引用。 Then form1 doesn't need to call form2 if it has been closed. 然后,如果form1已关闭,则不需要调用form2。

We do something similar here with a few of our tools that plug into third-party apps. 我们在这里使用插入第三方应用程序的一些工具来执行类似的操作。 Code sample below: 下面的代码示例:

public class Form1 : Form
{
    private Form2 otherForm;

    private void ActivateForm2_Click(object sender, EventArgs e)
    {
        if (otherForm == null || otherForm.IsDisposed)
        {
            otherForm = new Form2();
            otherForm.FormClosed += new FormClosedEventHandler(otherForm_closed);
        }
        otherForm.Show(this);
    }

    private void otherForm_Closed(object sender, FormClosedEventArgs e)
    {
        otherForm.Dispose();
        otherForm = null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM