Say if I listen for an event:
Subject.NewEvent += delegate(object sender, NewEventArgs e) { //some code });
Now how do I un-register this event? Or just allow the memory to leak?
Go to the objects tab, view the Document object (don't click on edit) and scroll down to Event Handlers. Select the one to delete and press delete.
You cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, go back to the code where you subscribe to the event, store the anonymous function in a delegate variable, and then add the delegate to the event.
Anonymous methods are a simplified way for you to assign handlers to events. They take less effort than delegates and are closer to the event they are associated with. You have the choice of either declaring the anonymous method with no parameters or you can declare the parameters if you need them.
Give your instance of the anonymous delegate a name:
EventHandler<NewEventArg> handler = delegate(object sender, NewEventArgs e) { //some code }; Subject.NewEvent += handler; Subject.NewEvent -= handler;
If you need to unregister an event, I recommend avoiding anonymous delegates for the event handler.
This is one case where assigning this to a local method is better - you can unsubscribe from the event cleanly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With