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:-

  1. Error Creating Window Handle.
  2. 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).

UserGDIcolumnselect

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…

http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx
http://www.codeproject.com/KB/cs/idispose.aspx

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’
http://blogs.msdn.com/oldnewthing/archive/2005/03/15/395866.aspx

About these ads
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: