c# dispose remove - Is it bad to not unregister event handlers?

1 Answers

Many people seem to think that it's only important to unsubscribe from events if the publisher is going to outlive the subscriber. I dislike that approach. An event subscriber which does not detach itself from the publisher creates some a nasty dependencies on the behavior of entities outside the publisher and subscriber. If a reference to the publisher is held longer than expected, that will keep the subscriber alive, along with any objects to which the subscriber holds a reference. If a large mass of abandoned objects are interconnected by event handlers, but no live reference exists to any of them, all the objects can be swept up by the garbage collector. If, however, someone somewhere unexpectedly keeps a reference to one of the objects, that may prevent any of them from being garbage-collected.

IMHO, it's much better to be proactive in removing event handlers than to abandon them and hope that everything gets cleaned up. Unless one can be certain that no unexpected references to the publisher can exist, such an approach is likely to 'mostly' work, but cause occasional memory leaks.

unsubscribe all events

If I have an application with only a few event handlers registered (and the objects using the events are not disposed until the application is closed), do I really need to worry about unregistering those handlers? The only good reason I could see is that there might be a little extra overhead if events are being fired that you dont necessarly care about (i.e you have multiple handlers registered to one event). Is there any other good reason to? Anyone run into major issues because they didnt unregister events?