We had problems with memory leaks in our application. I was able to reproduce one of the problems with the following simple example:
Replication setup
1) Create the following helper class that will be used to track the creation / destruction of the object.
public class TestObject
{
public static int Count { get; set; }
public TestObject()
{
Count++;
}
~TestObject()
{
Count--;
}
}
2) Create an MDI form with three buttons, the first button will create a new MDI child as follows:
private void ctlOpenMDI_Click(object sender, EventArgs e)
{
Form newForm = new Form();
newForm.MdiParent = this;
newForm.Tag = new TestObject();
newForm.Show();
}
The second button will be used the same way, but with a child form other than MDI:
private void ctlOpenNonMDIForm_Click(object sender, EventArgs e)
{
Form newForm = new Form();
newForm.Tag = new TestObject();
newForm.Show();
}
The third button will be used to collect garbage and then display how many instances of TestObject live:
private void ctlCount_Click(object sender, EventArgs e)
{
GC.Collect();
GC.WaitForPendingFinalizers();
MessageBox.Show("Count: " + TestObject.Count);
}
Replication steps
1) " MDI", MDI "". Count: 1. MDI , , - - .
:
MDI , 3 , . Count: 1. , MDI .
Counter-:
1) " -MDI", . . Count: 0, .
, :
Form form = new Form();
form.MdiParent = this;
form.Show();
form.Close();
. MDI, - ? ?
, , .