Memory Leak in My .Net Application
.Net does not make memory leaks a thing of the past….but it does very nicely take away most of the burden from developers.
Our WinForms app is due to go live very soon and we’ve noticed that we have a memory leak. These are the two errors we were receiving…
OUT OF MEMORY EXCEPTIONS
We were receiving two differnt types of exceptions:-
- Error Creating Window Handle.
- A Generic Error Occured in GDI+
The errors intermittently in random parts of the application but it did seem to occur more frequently in one ‘problem’ area.
IDENTIFYING A MEMORY LEAK
Open Task Manager, goto Views -> Select Columns and check USER Objects and GDI Objects. Why do we care about these? As it turns out, if either of these numbers hits 10000 you will get an out of memory exception. User objects produces the Handle error and GDI produces the GDI error (oddly enough).
Now run your app and watch those numbers. Ideally focus on one specific area where you can repeat an activity such as opening and closing a modal window (the memory leaks we had were occuring around creating and disposing controls.) If the numbers go up and never come down then it’s likely you have a leak (allow some time for the Garbage Collector – GC – to run).
PLEASE DISPOSE OF YOUR OBJECTS THOUGHTFULLY
So the app had a memory leak, what then? First I checked that IDispose was correctly and that we were calling Dispose where necessary.
I’m not going to discuss how to do this in this post but here’s a couple of links to get you started…
Once this was done the User Objects count was under control. GREAT….but the GDI count was improved but there was no doubt that it was still growing unchecked. So what then? This article led me to ANTS Profiler and few interesting discoveries that I’ll discuss in my next post…
Other Resource/Useful Links
This is a very interesting article about ‘Windows are not cheap objects’