Tuesday, August 05, 2008

Event subscriptions may lead to memory leaks

Even though the .NET runtime has a garbage collector that cleans up unused objects and frees the memory, it is still possible to write code that contains a memory leak. Often this is very subtle and the memory leak is not apparent at first sight.

One of these subtle memory-leaks may occur if your code subscribes to an event, but never unsubscribes. Whenever a subscriber subscribes to an event that is published by the publisher, the publisher will hold a reference to the subscriber.

I tried to visualize this in this diagram:

SubscriberAndPublisher

The publisher will hold this reference as long as the event is not unsubscribed. So as long as the publiser is alive, the garbage collector will not collect the subscriber-objects. This leads to a memory leak (or sometimes worse, if the subscriber holds other resources such as files or threads).

Typically this occurs when the publisher is a static object (which lives as long as the process lives).

So whenever you subscribe to an event, think whether it is necessary to unsubscribe from this event (especially if the publisher has a long lifetime).

Of course the same thing occurs in every situation where a static (or long-lived) object has a reference to other (short-lived) objects. Always consider when this reference should be removed again!

1 comment:

Steven said...

That's the reason WPF uses the Weak Event Pattern. The Weak Event Pattern solved the memory leak problem.