I have a class that offers up a few events. That class is declared globally but not instanced upon that global declaration–it's instanced on an as-needed basis in the methods that need it.
Each time that class is needed in a method, it is instanced and event handlers are registered. Is it necessary to remove the event handlers explicitly before the method goes out of scope?
When the method goes out of scope, so goes the instance of the class. Does leaving event handlers registered with that instance that is going out of scope have a memory footprint implication? (I'm wondering if the event handler keeps the GC from seeing the class instance as no longer being referenced.)
In your case, everything is fine. It's the object which publishes the events which keeps the targets of the event handlers live. So if I have:
publisherhas a reference to
targetbut not the other way round.
In your case, the publisher is going to be eligible for garbage collection (assuming there are no other references to it) so the fact that it's got a reference to the event handler targets is irrelevant.
The tricky case is when the publisher is long-lived but the subscribers don't want to be - in that case you need to unsubscribe the handlers. For example, suppose you have some data transfer service which lets you subscribe to asynchronous notifications about bandwidth changes, and the transfer service object is long-lived. If we do this:
(You'd actually want to use a finally block to make sure you don't leak the event handler.) If we didn't unsubscribe, then the
BandwidthUIwould live at least as long as the transfer service.
Personally I rarely come across this - usually if I subscribe to an event, the target of that event lives at least as long as the publisher - a form will last as long as the button which is on it, for example. It's worth knowing about this potential issue, but I think some people worry about it when they needn't, because they don't know which way round the references go.
EDIT: This is to answer Jonathan Dickinson's comment. Firstly, look at the docs for Delegate.Equals(object) which clearly give the equality behaviour.
Secondly, here's a short but complete program to show unsubscription working:
(Tested on Mono and .NET 3.5SP1.)
This is to prove that an event publisher can be collected while there are still references to a subscriber.
Results (in .NET 3.5SP1; Mono appears to behave slightly oddly here. Will look into that some time):