.NET memory leaks with event handlers
One of the biggest pains (and biggest benefits) of working with C++ is memory management. It is quite easy to create a memory leak and C++ and often difficult to later discover where the leak originated.
One of the biggest benefits of C# is that memory management is handled for the developer (through garbage collection). Well…. not so fast. I’ve discovered a serious memory leak within the .NET MenuItem that is quite easy to duplicate. Most applications do not create and destroy too many windows so a small leak here is not a big deal. However, the application I have been working on uses hundreds of windows! Here are the details…
When we create forms in .NET and double-click on buttons on textboxes, Visual Studio will automatically stub out the event handlers within the ‘InitializeComponent’ method. If you take a look at this method you’ll see several event handlers ‘wired’ up through the ‘+=’ syntax. However, you don’t see any corresponding ‘-=’ syntax to disconnect the event. For the most part, that’s ok because the CLR takes care of cleaning up and destroying the form and its event handlers. There is 1 exception…. MenuItems.
The problem:
I’ve discovered that any event handlers that .NET automatically generates for MenuItems result in memory leaks.
The solution:
To fix this memory leak you must implement Dispose and explicitly release these MenuItem event handlers through the ‘-=’ syntax.
Also, any event handlers you setup on your own (outside of InitializeComponent) must also be explicitly released.
However, keep in mind that there is a specific way to implement a destructor in .NET as you don’t want to the garbage collector to call ‘Dispose’ twice. An example follows (our search MSDN):
public class Foo: IDisposable
{
public Foo()
{
}
~Foo()
{
this.Dispose();
}
public void Dispose()
{
// TODO : Release all EventHandlers
GC.SuppressFinalize(this);
}
}
NOTE: I used ‘.NET Memory Profiler’ to help aid in finding the cause of these memory leaks. It is a great tool for quickly isolating these kinds of problems.

1 Comments:
test me
Post a Comment
<< Home