Should I always disconnect event handlers in the Dispose method?

Unless you expect the publisher of the event to outlive the subscriber, there’s no reason to remove the event handler, no.

This is one of those topics where folk lore has grown up. You really just need to think about it in normal terms: the publisher (e.g. the button) has a reference to the subscriber. If both the publisher and the subscriber will be eligible for garbage collection at the same time anyway (as is common) or if the publisher will be eligible for garbage collection earlier, then there’s no GC issue.

Static events cause a GC problem because they’re effectively an infinitely-long-lived publisher – I would discourage static events entirely, where possible. (I very rarely find them useful.)

The other possible issue is if you explicitly want to stop listening for events because your object will misbehave if the event is raised (e.g. it will try to write to a closed stream). In that case, yes, you should remove the handler. That’s most likely to be in the case where your class implements IDisposable already. It would be unusual – though not impossible – for it to be worth implementing IDisposable just to remove event handlers.

Leave a Comment