InfoQ

News

Dealing with Memory Leaks in .NET

Posted by Abel Avram on Nov 05, 2009

Community
.NET
Topics
Programming
Tags
Memory Leaks ,
GarbageCollection

Fabrice Marguerie, a software architect and consultant, wrote the article How to detect and avoid memory and resources leaks in .NET applications, published on MSDN. The article explains how memory and resource leaks can happen while programming for .NET and how to avoid them.

Languages like C#, doing house cleaning through a memory garbage collector, do not have memory leaks in its original sense when a program loses complete access to a memory location. According to Fabrice, memory leaks take place when a memory location is no longer needed but the program continues to keep at least one reference to it. The garbage collector would reclaim that memory if it was unreachable, but the memory becomes a leak as long as it is referenced by the program but not used.

Fabrice also lists a number of OS resources which can be subject to similar leaks:

  • The system uses User objects to support window management. They include: Accelerator tables, Carets, Cursors, Hooks, Icons, Menus and Windows.
  • GDI objects support graphics: Bitmaps, Brushes, Device Contexts (DC), Fonts, Memory DCs, Metafiles, Palettes, Pens, Regions, etc.
  • Kernel objects support memory management, process execution, and inter-process communications (IPC): Files, Processes, Threads, Semaphores, Timers, Access tokens, Sockets, etc.

These resources are limited, the registry keys GDIProcessHandleQuota and USERProcessHandleQuota containing the maximum number of GDI and user objects a process can use. The default values are 10,000 for these handles. While the number is enough for most applications, using too many of them will make the system reach another limit of 65,536 handles for a Windows session. Fabrice reported hitting that limit a lot sooner, at about 11,000. His conclusion is that systems resources need to be carefully used and freed when no longer needed.

Fabrice lists the following root causes for leaks explaining how each of them works:

  • Using static references
  • Event with missing unsubscription – these are considered by the author to be the most common source of leaks
  • Static event with missing unsubscription
  • Not invoking the Dispose method
  • Using an incomplete Dispose method
  • Misusing BindingSource  in Windows Forms
  • Not using Remove call on WorkItem/CAB

The author continues the article by offering advice on how to avoid leaks:

  • the creator or owner of an object, not its user, is responsible for disposing it
  • always unsubscribe an event listener when it is not longer needed; it could be done in Dispose() for safety
  • when an object no longer generates events, all its listeners should be removed by assigning null to the object
  • when a reference is used by a model and its view, it is recommended to pass a clone of the referenced object to the view to avoid losing track of who’s using what
  • calls to system resources should be enclosed in using blocks which automatically force a Dispose call when leaving the block

Fabrice concludes by introducing a number of useful tools for dealing with objects and leaks: GDILeaks (EXE), dotTrace, .NET Memory ProfilerSOS.dll, WinDbg.

I would add... by Francois Ward Posted Nov 5, 2009 10:15 AM
Re: I would add... by Fabrice Marguerie Posted Nov 5, 2009 2:13 PM
French version by Fabrice Marguerie Posted Nov 5, 2009 2:16 PM
  1. Back to top

    I would add...

    Nov 5, 2009 10:15 AM by Francois Ward

    The most common case that I've seen as an ASP.NET development is the caching of complex UI objects (which should never be done), since these have references to nearly everything in the application life cycle, causing entire contexts to stay in memory.

    Also, i think no discussion about .NET memory leak (or Java, for that matter) is complete without talking about WeakReferences (references that allow the garbage collector to clean the objects if no other references are found)

  2. Back to top

    Re: I would add...

    Nov 5, 2009 2:13 PM by Fabrice Marguerie

    I'll give more cases soon on my blog, based on what I've discovered since I wrote this article.

    WeakReferences are covered in the article, even if I just give a hint at them.

  3. Back to top

    French version

    Nov 5, 2009 2:16 PM by Fabrice Marguerie

Educational Content

Brian Marick on 4 Challenges and 5 Guiding Values of Agile Software Development

Brian Marick takes us through a quick tour of the most important values and challenges to adopting Agile successfully (they aren't the typical challenges and values we hear in the community).

Are You a Software Architect?

The line between development and architecture is tricky. Does it exist at all? Is an ivory tower actually needed? There's a balance in the middle, but how do you move from developer to architect?

Agile – A Way of Life and Pragmatic Use of Authority

The word 'authority' sometimes produces an allergic response in hard-line agilists. Freedom and authority – both are bad if misused and both are good if used in right spirit for a noble cause.

Getting Started with Grails, Second Edition

"Getting Started with Grails" brings you up to speed on this modern web framework. Companies as varied as LinkedIn, Wired, and Taco Bell are all using Grails. Are you ready to get started as well?

Using ITIL V3 as a Foundation for SOA Governance

Those familiar with only ITIL V2 often scoff at the thought that ITIL could serve as a governance framework for SOA. With ITIL V3, the focus of the framework shifted towards service-orientation.

Adrian Colyer on AspectJ, tc Server and dm Server

SpringSource CTO Adrian Colyer discusses AspectJ, SpringSource's dm Server and tc Server products, OSGi and Scrum.

Adam Wiggins on Heroku

Heroku's Adam Wiggins talks about Rails, Background Jobs, Add-Ons, Ruby, and how Heroku manages to work around Ruby's inefficiencies using Erlang and other languages.

SOA as an Architectural Pattern: Best Practices in Software Architecture

For Grady Booch the foundation of a good architecture is patterns, SOA being just one of many patterns. In this Second Life presentation, Booch attempts to bring more clarity on what architecture is.