Code Analysis Complains about "CA2000 Dispose objects before losing scope" when I Don't Dispose My MDI Child Form

StackOverflow https://stackoverflow.com/questions/21281841

Domanda

CA2000 Dispose objects before losing scope

In method FormMain.barButtonItem1_ItemClick(object, ItemClickEventArgs)

Call System.IDisposable.Dispose on object 'frm' before all references to it are out of scope. Winpro FormMain.cs 32

Method :

private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
    FormCustomerList frm = new FormCustomerList();
    frm.MdiParent = this;
    frm.Show();
}

This is not a serious problem, but why is this fired?

I can't use finally frm.Dispose() or using() because form will not be shown.

I have also tried to handle form closing and then dispose but violation is always here.

È stato utile?

Soluzione

Code Analysis can't tell that frm is still doing anything after it exits scope. In this specific case, the object needs to stay alive after the function is done with it.

The "correct" way to handle this is to maintain a reference to frm in the parent form. This reference can then be disposed in the Dispose() method of the parent form.

private FormCustomerList frm;
private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
    frm = new FormCustomerList();
    frm.MdiParent = this;
    frm.Show();
}

If you have multiple sub forms that can be created (which is likely if you're using MDI), you can maintain a List<> of child forms.

private List<FormCustomerList> frms = new List<FormCustomerList>();
private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
    FormCustomerList frm = new FormCustomerList();
    frms.Add(frm);
    frm.MdiParent = this;
    frm.Show();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top