Memory and Resource Leaks in .NET Applications

The following is a (quite) short summary of this MSDN article

Firstly, it is of vital importance to understand that a Garbage Collected environment such as Managed .NET is not immune to memory leaks. One of the reasons for this is the fact that .NET's Garbage Collector only disposes objects which are no longer referenced by any other object. Ergo, if an object's reference count does not reach zero because of a dangling reference, the GC won't save us.

On the other hand, when we talk about .NET applications which run on Windows, said applications usually consume Operating System resources (bitmaps, thread handles, critical sections, etc). These should be, ideally, released as soon as they are no longer needed.

The author of the MSDN article mentions a ninja technique to hunt down leaks:

Nevertheless, he prefers using higher level tools, such as these

Usual causes for memory leaks in .NET:
  1. Static references (static state and Singletons). Besides, an undisposed static object which contains or references other objects or resources prevents them from being disposed...
  2. Events whose handlers are not unregistered (-= in C#, RemoveHandler in VB-NET)
  3. Not calling Dispose() for those objects whose class implements IDisposable
  4. Incomplete or defective implementation for IDisposable::Dispose in one of our classes
  5. Bugs in third party libraries used by our project, or in .NET (only consider this after thoroughly proving that our code is clean)
After showing a few examples pf leaks and techniques to solve them using the dotTrace tool, the author mentions a few good practices to prevent introducing leaks:
  1. Every object which creates an object is responsible for its disposal (ideally, using RAII semantics), except when the Factory design pattern is used. In that case, the object which uses the Factory must be the one who disposes of the object either directly or calling the Factory.
  2. Events are the main cause of memory leaks in .NET. Whenever you write code to register them, write code to unregister them.
  3. Always call Dispose for our IDisposable classes, and update them thoroughly when we add resources to our classes' state.

Finally, the author recommends a series of very interesting tools. This is better seen in the original article.

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

Upgrading Lodash from 3.x to 4.x