Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Unregister 'anonymous' event handler [duplicate]

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?

like image 902
P.K Avatar asked Aug 28 '09 16:08

P.K


People also ask

How do I delete an event handler?

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.

How to unsubscribe from event c#?

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.

Why do we use anonymous event handlers in Windows Forms?

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.


2 Answers

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; 
like image 93
dtb Avatar answered Sep 24 '22 09:09

dtb


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.

like image 38
Reed Copsey Avatar answered Sep 22 '22 09:09

Reed Copsey