More... (.NET can Leak Managed Memory?)

Potentially the most common pattern creating managed memory leaks:

public class SomeClass
{
    public static event EventHandler SomeStaticEvent;
}
The why of this specific leak is a wonderful .NET test question, because it’s completely hidden from
view, though it makes perfect sense once revealed. What must .NET have in order to make a call back
to an event handler method in the context of another object? Why a reference to the target class
possessing the handler method of course.

This means that .NET does a little ‘black magic’ when event wire-up code, such as that below, is
executed (commonly called subscribing to the event.)

SomeClass.SomeStaticEvent += new EventHandler(SomeOtherClass_SomeHandler);
Every time this code is executed, .NET adds the SomeOtherClass_SomeHandler to the invocation list
of the SomeStaticEvent delegate. If SomeOtherClass_SomeHandler is not a static method, during
the add .NET also records a reference to the target class owning SomeOtherClass_SomeHandler.

The end result is that if there is not an unsubscribe call for each and every event subscription, memory
will leak, indefinitely. Make SomeOtherClass_SomeHandler a handler owned by a complex UI Form
with many controls laden with data and you can get a sense what might happen every time users move
in and out of a Form subscribing to static events.

Why Use It?

If the pattern is so problematic, why is everyone using it? Simple. In complex, interdependent
frameworks with many moving parts, employing a static event as a reflection point is the easiest and
often the only way to allow all the parts to communicate. The approach is also a pattern that promotes
loose coupling between parts, which is always desirable.

The problem is not the pattern itself, but one of discipline and time. Discipline in ensuring every object
subscribing to a static event is unsubscribed. Time in clearly conveying the intent of the framework
through code so that future generations of developers charged with the task of maintaining and
extending your wonder creation know how to properly handle the pattern.

Unmanaged Leaks

The third most common .NET leak is unmanaged memory, which cannot be cleaned through internal
means, since .NET does not actually own this memory. Though MemClean!, being the caring framework
that it is, will call Dispose on your behalf during cleanup, which resolves most unmanaged memory leak
scenarios when dealing with .NET base classes.

Last edited Sep 29, 2009 at 4:11 AM by theMont, version 1

Comments

No comments yet.