.NET Framework - unregister event handlers?

Asked By Anders Eriksson on 04-Aug-11 09:47 AM
If I have registered an event handler
LE_System.sigLaserEnd += new
laserengineLib.ISystemEvents_sigLaserEndEventHandler(LE_System_sigLaserEnd);

Is it necessary (or good practice) to unregister it when the program ends?

LE_System.sigLaserEnd -= new
laserengineLib.ISystemEvents_sigLaserEndEventHandler(LE_System_sigLaserEnd);

// Anders




Peter Duniho replied to Anders Eriksson on 04-Aug-11 10:39 AM
When the program ends?  No, not at all.  Object lifetime has no effect
on the termination of the program; the program will exit normally, and
all objects not yet freed will be discarded as part of the termination
process.

However, you definitely need to watch out for accidentally leaving an
event handler subscribed when the object owning the handler is otherwise
supposed to be unreachable and discardable.  This causes two problems:

??? Event handlers that get called when you did not expect them to, on
objects that you thought were gone
??? Objects staying alive when you thought they would not

Both problems can be serious issues.  The former can lead to errativ
behavior in the program, and the latter can result in excessive memory
usage.

Note that if the object containing the event is itself not reachable,
then the event referencing other objects does not cause those other
objects to remain reachable, and all are eligible for garbage collection
if they are otherwise not reachable by other means.  it is only when the
object containing the event continues to be used, while the objects with
the event handlers were otherwise unused.

But in any case, at program exit none of that matters.  Reachability of
objects does not in and of itself affect whether the program can exit,
and all memory referenced by the program is released when the program exits.

One final caveat: there are in fact specific static events declared by
classes in the .NET framework itself that should be unsubscribed before
program exit.  But these are uncommon, and the documentation for each is
clear about the need to unsubscribe.  You will not run into that situation
accidentally.

Pete