InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

Dealing with Memory Leaks in .NET

Posted by Abel Avram on Nov 05, 2009

Sections
Development,
Architecture & Design
Topics
.NET ,
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
Re: I would add... by Fabrice Marguerie Posted
French version by Fabrice Marguerie Posted
  1. Back to top

    I would add...

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

    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

    by Fabrice Marguerie

Educational Content

Collaboration: At the Extremities of Extreme

Jason Ayers share the observations he made watching a team of developers collaborating in real time on the same code base, pushing XP, pair programming and continuous integration to their extremes.

Yesod Web Framework

Michael Snoyman presents Yesod, a web framework written in Haskell and containing a web server, templating, ORM, libraries (templating, gravatar, etc.).

Transactions without Transactions

Richard Kreuter and Kyle Banker on how to avoid classical RDBMS transactional systems by using compensation mechanisms, transactional messaging or transactional procedures.

Attila Szegedi on JVM and GC Performance Tuning at Twitter

Attila Szegedi talks about performance tuning Java and Scala programs at Twitter: how to approach GC problems, the importance of asynchronous I/O, when to use MySQL/Cassandra/Redis, and much more.

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.

Interview: Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives

InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.

Beauty Is in the Eye of the Beholder

Alex Papadimoulis discusses ugly code, where it comes from, how to avoid it, and how to get rid of it.

Architecting Visa for Massive Scale and Continuous Innovation

John Davies examines Visa’s architecture and shows how enterprises have architected complex integrations incorporating Hadoop, memcached, Ruby on Rails, and others to deliver innovative solutions.