Is it bad to not unregister event handlers?

C#EventsEvent Handling

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

If you have A publishing an event, and B subscribing to an event (the handler), then it is only a problem not to unsubscribe if A is going to live a lot longer than B. Basically, the event subscription means that A can still see B, so would prevent it from being garbage collected, and would still fire events on it even if you've forgotten about it (and perhaps Disposed() it).

For example, this is a problem if A is a static event, and your app runs for a while after B dies... ButB will live as long as A , thus B will not be garbage collected.

It is important to note, one might ask the following:

> if B lives a lot longer than A, will B keep A from being garbage collected?

And the answer to that is "no". B has no reference to A through the event; A will be collected as normal

Solution 2 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSwDevMan81View Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#supercatView Answer on Stackoverflow