ObjectDisposedException when .Show()'ing a form that shouldn't be disposed.

Posted by user320781 on Stack Overflow See other posts from Stack Overflow or by user320781
Published on 2010-04-19T21:57:04Z Indexed on 2010/04/24 5:53 UTC
Read the original article Hit count: 270

ive checked out some of the other questions and obviously the best solution is to prevent the behavior that causes this issue in the first place, but the problem is very intermittent, and very un-reproduceable.

I basically have a main form, with sub forms. The sub forms are shown from menus and/or buttons from the main form like so:


private void myToolStripMenuItem_Click(object sender, EventArgs e)
{
    try
    {
        xDataForm.Show();
        xDataForm.Activate();
    }
    catch (ObjectDisposedException)
    {
        MessageBox.Show("ERROR 10103");
        ErrorLogging newLogger = new ErrorLogging("10103");
        Thread errorThread = new Thread(ErrorLogging.writeErrorToLog);
        errorThread.Start();
    }
}

and the sub forms are actually in the main form(for better or worse. i would actually like to change this but would be a considerable amount of time to do so):


public partial class FormMainScreen : Form
{
    Form xDataForm = new xData();
    ...(lots more here)

    public FormMainScreen(int pCount, string pName)
 {
        InitializeComponent();
        ...
 }
    ...
}

The Dispose function for the sub form is modified so that, the 'close' and 'X' buttons actually hide the form so we dont have to re-create it every time. When the main screen closes, it sets a "flag" to 2, so the other forms know that it is actually ok to close;


protected override void Dispose(bool disposing)
{
    if (FormMainScreen.isExiting == 2) 
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }
    else
    {
        if (xData.ActiveForm != null)
        {
            xData.ActiveForm.Hide();
        }
    }
}

So, the question is, why would this work over and over and over again flawlessly, but, literally, about every 1/1000 of the time, cause an exception, or rather, why is my form being disposed?

I had a suspicion that the garbage collector was getting confused, because it occurs slightly more frequently after it has been running for many hours.

© Stack Overflow or respective owner

Related posts about c#

Related posts about objectdisposedexception