Why and How to avoid Event Handler memory leaks?

The cause is simple to explain: while an event handler is subscribed, the publisher of the event holds a reference to the subscriber via the event handler delegate (assuming the delegate is an instance method).

If the publisher lives longer than the subscriber, then it will keep the subscriber alive even when there are no other references to the subscriber.

If you unsubscribe from the event with an equal handler, then yes, that will remove the handler and the possible leak. However, in my experience this is rarely actually a problem – because typically I find that the publisher and subscriber have roughly equal lifetimes anyway.

It is a possible cause… but in my experience it’s rather over-hyped. Your mileage may vary, of course… you just need to be careful.

Leave a Comment