Well in line with my last
post one of the reasons for one of the many (many) memory leaks we encountered was due to controls being added to a form programmatically, and then being 'cleared' but not disposed e.g.
Controls.Clear(). Turns out this *doesn't* actually free up the memory that these controls use, all it seems to do is remove the objects from the collection. To ensure those controls do actually get removed and GC'd you've got to individually
Dispose() them as well, which led to this helper method:
private void disposeControls(ControlCollection controls)
{
for (int i = controls.Count - 1; i >= 0; i--)
{
Control control = controls[i];
control.Dispose();
}
controls.Clear();
}
You'll notice we do a reverse iteration of the controls in the collection, because if you started at the beginning, every time you dispose a control it actually shifts the other controls in the collection down one index, causing only about half of the controls to be successfully disposed.
Thanks to
this guy for the tip.