简体   繁体   中英

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. Then form1 doesn't need to call form2 if it has been closed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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