Memory Leaks in .NET Applications

Posted by Hugh Ang at 1/23/2007 10:54:00 AM

When I tell people that their .NET applications are leaking memory, I sometimes get frowned upon as if memory leaking is moot in CLR. After all, garbage collection is there so why would we have to worry about this?

MSDN has published an excellent article on this topic. While it covers many memory leaking scenarios to watch out for, I have seen a couple of quite common ones at various customers due to coding practice issues:

1) Custom-rolled caching that has no expiration and throttling mechanisms. The cache eventually will be filled up with references to objects that are not intended to be kept. A common pattern is a singleton wrapping a hashtable.

2) Event handlers (delegates) added to application level events but forgotten to be removed. I have seen this in both Winform and ASP.NET apps, where a form or an ASP.NET page has hooked its instance function to an application event through a delegate. Forgetting to remove such handlers when the form or page is unloaded will simply keep the instance of the form or page in memory, keeping it from garbage collected.

As you can see, just like you need to "free" after "malloc", "delete" after "new", "CloseHandle" after "CreateFile" etc. in C++/Win32 API, discipline is still needed in .NET coding just as well. So don't let your guard down.