Sunday, July 1, 2007

Leaking Form.ShowDialog

In the last few weeks I was debugging an application to find leaking memory. I found lots of tips in this MSDN article. Something I found few times is that people are not aware that you MUST call Dispose() after you call ShowDialog (see Microsoft docs).

The simplest way to create a memory leak with a form:
Form form = new FooForm();
form.Owner = this
After this code block will finish the form "form" will stay in the memory because the owner form holds a refrence to the form in OwnedForms. To free the memory you must call form.Dispose();