ObjectDisposedException when .Show () 'is a form that should not be removed

ive checked some other questions, and obviously the best solution is to prevent the behavior causing this problem in the first place, but the problem is very intermittent and very irreproducible.

I basically have a basic form with subforms. Subforms are displayed from the menu and / or buttons from the main form as follows:


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 subforms are actually in the main form (better or worse, I would really like to change that, but it would take a considerable amount of time):


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

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

Dispose , "close" "X" , . , "" 2, , ;


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

, , , , , 1/1000 , , , ?

, , , .

+3
2

, , , , .

Dispose(), ( , .) , .

, , , , Dispose.

, , MDI ( ) , "" MDI. FormClosing .

( : MDI, , .)

// MDI child
private void Form_FormClosing(object sender, FormClosingEventArgs e) {
    if (e.CloseReason == CloseReason.UserClosing) {
        e.Cancel = true;
        Hide();
    }
}

- , , , Windows .., . , , .

MDI MDI, :

MyParentForm parentForm = new MyParentForm();
parentForm.IsMdiContainer = true;
parentForm.Show();

MyChildForm childForm = new MyChildForm();
childForm.MdiParent = parentForm;
childForm.Show();
+3
try 
{
    // Validate form not disposed before using. Initialize as needed. 
    if  (xDataForm == null || xDataForm.IsDisposed)
    {
        xDataForm = new MyDataFormName();
    }
    xDataForm.Show(); 
    xDataForm.Activate(); 
} 
+2

Source: https://habr.com/ru/post/1741844/


All Articles