Preventing Event-based Memory Leaks – WeakEventManager

Events are a common source of memory leaks in .NET applications.

When an object (the receiver) subscribes to an event on another object (the sender), the sender holds a reference to the receiving object.  This is because the standard event mechanism in .NET works based off delegates, which contain two member fields – _target and _methodPtr.  In this case, _target acts as a strong reference to the receiver.  Later, if the receiver is no longer needed, it must unsubscribe from the event, or the event itself will keep the receiving object rooted, preventing the garbage collector from reclaiming its memory.  This can lead to large memory leaks – especially if the receiver itself holds large amounts of memory.

Normally, this isn’t a problem; its easy to just unsubscribe from the event, which prevents the above from occurring.  However, there are times when the useful lifetime of a receiver of an event isn’t tied to the sender at all, which can make unsubscribing very difficult.  WPF introduced a new class and pattern for handing this situation: the WeakEvent Pattern.

Read more