Memory leaks in a Windows Forms application
Solution 1
The first place to look for leaks is in event-handling rather than missing Dispose()
calls. Say your container (the parent form) loads a child form and adds a handler for an event of that child form (ChildForm.CloseMe
).
If the child form is intended to be cleared from memory then this event handler must be removed before it is a candidate for garbage collection.
Solution 2
Disposing the forms is not necessarily a guarantee that you are not leaking memory. For example, if you are binding it to a dataset but you are not disposing of the dataset when you are done, you will probably have a leak. You may need to use a profiling tool to identify which disposable resources are not being released.
And btw, calling GC.Collect() is a bad idea. Just saying.
Solution 3
The most common source of memory leaks in Windows Forms applications is event handlers that remain attached after form disposal...so this is a good place to start your investigation. Tools like http://memprofiler.com/ can help greatly in determining roots for instances that are never being GC'd.
As for your call to GC.Collect
- It's definitely not good to do this in practice
-
In order to make sure your GC collect really does collect as much as possible, you need to make multiple passes and wait for pending finalizers, so the call is truly synchronous.
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers();
Also, anything that holds on to your instance of your form will keep the form around in memory, even after it's been Closed and Disposed.
Like:
static void Main() {
var form = new MyForm();
form.Show();
form.Close();
// The GC calls below will do NOTHING, because you still have a reference to the form!
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
// Another thing to not: calling ShowDialog will NOT
// get Dispose called on your form when you close it.
var form2 = new MyForm();
DialogResult r = form2.ShowDialog();
// You MUST manually call dispose after calling ShowDialog! Otherwise Dispose
// will never get called.
form2.Dispose();
// As for grids, this will ALSO result in never releasing the form in
// memory, because the GridControl has a reference to the Form itself
// (look at the auto-generated designer code).
var form3 = new MyForm();
form3.ShowDialog();
var grid = form3.MyGrid;
// Note that if you're planning on actually using your datagrid
// after calling dispose on the form, you're going to have
// problems, since calling Dipose() on the form will also call
// dispose on all the child controls.
form3.Dispose();
form3 = null;
}
Solution 4
I recently had a similar issue where a running timer kept the form in memory, even though the form was closed. The solution was to stop the timer before closing the form.
Related videos on Youtube
Kashif
Updated on July 09, 2022Comments
-
Kashif almost 2 years
We are developing a big .NET Windows Forms application. We are facing a memory leak/usage problem in that despite we are disposing the forms.
The scenario is like:
- Our application is using 60 KB of memory with a list of records displaying in a grid.
- When the user clicks on a record it opens a form,
myform.showDialog
, show the details. The memory jumps from 60 KB to 105 MB. - Now we close the form
myform
to get back to grid, and dispose that form and set it to null. Memory remains at 105 MB. - Now if we again perform step 2, it would jump from 105 MB to 150 MB and so on.
How can we free up the memory when we close
myForm
?We have already tried
GC.Collect()
, etc., but without any result.-
Andrew Barber over 13 yearsHow far does the "and so on" go? Honestly, you aren't talking about significant amounts of memory here, and the GC likely won't even try to free memory at those levels.
-
We Are All Monica over 13 yearsI think you mean "60M to 105M" instead of "60K to 105K". 150K is nothing.
-
Miguel over 10 yearsI have the same issue and the memory usage can grow up until 1.5 Gb (Gigabyte)
-
Andrew Barber over 13 years+1
GC.Collect()
being called is frequently evidence of bad programming (even if the bad programming is just the GC.Collect() call itself) -
Mark Simpson over 13 years+1 -- Beat me to it. This is definitely the most common form of memory leak I've run into with .NET
-
Hogan over 13 years@Andrew : you can conceive of no case where calling GC.Collect() would be a good idea?
-
Andrew Barber over 13 years+1 Also, the .NET GC works in 'generations'; even if you are 100% sure there are no remaining references to a form or other object, calling
GC.Collect()
does not guarantee the memory will be freed. Objects which survive a GC can be promoted to a higher generation, meaning they will be checked less frequently for collection. -
Andrew Barber over 13 years@Hogan : If I could conceive of no case for calling
GC.Collect()
, I would have used the word always rather than frequently. -
STW over 13 yearsYep. We had a ton of WinForms code when we started getting reports of
OutOfMemoryExceptions
which led to months of end of hunting down these types of leaks. Definately a pain! I'm still upset that MS's documentation onAddHandler / +=
calls doesn't have a huge, blinking warning about needing to guaranteeRemoveHandler / -=
is called -
Otávio Décio over 13 years@Andrew - very good point. I've heard of cases where calling GC.Collect() makes the situation worse exactly because of promotion.
-
STW over 13 yearsIt might be what you're getting at, but there are certain constructors for
XmlSerializer
which also dynamically generate and load a new assembly every time they're called--if you don't manually cache and retrieve their results then they can quickly become a leak -
Aliostad over 13 years1st generation is only 2 MB (although nowadays it could be different from machien to machine)
-
STW over 13 years@Hogan -- The guidelines are quite clear: DON'T! Sure there are valid reasons to do it, but those reasons exist for the extreme minority of applications (such a small minority that you can safely assume you aren't in it). So, again DON'T!. GC is a very expensive and slow operation (especially pre .NET 4), it is also a fully automated process--so manually calling it is wasteful.
-
Otávio Décio over 13 years@Hogan - It was pointed out in another answer that it is possible to make matters worse by calling GC.Collect() due to generation promotion.
-
Travis Gockel over 13 years+1 for the most common cause of a memory leak in .NET. I wish MS had made the
void Dispose(bool disposing)
pattern ( msdn.microsoft.com/en-us/library/fs2xkftw.aspx ) much more obvious in the documentation as well as the+=
and-=
for event handlers. -
STW over 13 years@Travis : funny you should mention
Dispose(bool)
. One of my first SO questions was about that: stackoverflow.com/questions/773165/… -
Jeff over 13 yearsJust noting, since the GC does handle circular references, unless you have an EventHandler rooted outside of the form control hierarchy, it's not necessary to actually remove your handlers explicitly (-=)
-
Kashif over 13 yearsWe are using Telerik controls.
-
STW over 13 years@Jeff -- correct; entire portions of the object graph can be collected provided they are unreachable. However, I'd advise adding the extra
RemoveHandler / -=
calls just to help play it safe--especially if GC is not well understood -
Jeff over 13 yearsIt may not reflect the released memory in the task manager until the second GC call or until you wait for pending finalizers. Your statement about Disposing after you call ShowDialog is incorrect. See "Why you must Dispose() after calling ShowDialog()" under the Microsoft article msdn.microsoft.com/en-us/library/…
-
STW over 13 yearsyou mentioned the Task Manager, which is a TERRIBLE means of measuring .NET memory usage. Use
perfmon
's Process metrics for things like Private Bytes instead. Task manager used to show us ~95% memory reduction just by minimizing and restoring the application, just as evidence of how off-the-mark its reporting is. -
Jeff over 13 yearsYes, I'm aware of the "minimize and suddenly your application is mega memory conservative" effect :)
-
Patrick over 13 yearsTechnically, there is no need to call Dispose() on Datasets and DataTables, as they suppress finalization in their constructors. They don’t have unmanaged resources; so despite the fact that MarshalByValueComponent makes allowances for unmanaged resources, these particular implementations don’t have the need and can therefore forgo finalization.
-
Dan Bryant over 13 yearsYou're correct, ShowDialog() does only Hide when the form is closed; I retract my comment. It is still true that form becomes eligible for collection after the last time it is referenced within the method, however.
-
Hogan over 13 years@Andrew -- fair point. @STW, @Otávio Décio -- missed my point. :D
-
Jeff over 13 yearsIt took me four years of WinForms programming to realize the bit about ShowDialog()...and it was only a very painful experience that taught me that. :D