I would like to confirm something – when I register a method as a subscriber to an event the long way, like so:
_serviceContext.ReadingEntity += new EventHandler<ReadingWritingEntityEventArgs>(_serviceContext_ReadingEntity);
I need to un-register that method from the event’s subscription if I don’t want it to continue to be called when the event is fired, like this:
_serviceContext.ReadingEntity -= new EventHandler<ReadingWritingEntityEventArgs>(_serviceContext_ReadingEntity);
When I register a delegate as a subscriber to an event, like so:
public guy ThisMethod()
{
_serviceContext.ReadingEntity += delegate(object sender, ReadingWritingEntityEventArgs e)
{
};
}
There is no way to un-register that delegate from the subscriber list from that method. So I am assuming that the scope of this registration is limited to the method in which it’s registered – i.e. if the _serviceContext.ReadingEntity event was fired in a method called by ThisMethod, this registration would be already expired and the code inside the delegate would not run. Is this correct?
Thanks!
p.s. I realize that the first “long” way of registering an event handler also has scope limitations, but I’m a bit hazy on that. My main question, however, is whether or not the delegate registration will live on outside of the method above.
Once you subscribed a delegate this way (you can unsubscribe using
-=operator if you cache the delegate variable somewhere) you can’t remove it from subscribers list and it will be invoked every time event rises until publisher is alive. Moreover this subscription will prevent any subscriber class (class which contains the method you subscribed to event) from garbage collection until publisher is alive (unless you use a static method).To give some clarity, there is no “anonymous” methods in IL code. All your delegates and lamdbas are translated into static/instance methods and closure classes (depends on whether they use instance members/function parameters).