How can I unregister an anonymous handler?

C # 2.0 has a neat feature called anonymous functions. This is intended for use mainly with events:

Button.Click += delegate(System.Object o, System.EventArgs e) { System.Windows.Forms.MessageBox.Show("Click!"); }; 

Now suppose Button is a static member, then adding delegates to it will be considered unmanaged resources. Normally, I would have to unregister the handler before overwriting it again. This is a fairly common example of using GUI programming.

What are the recommendations with anonymous features? Does this happen evenly? If yes, then when?

+4
source share
2 answers

No, anonymous functions will not be automatically canceled. You must make sure that you do this yourself if this event should not be connected during the entire life of your application.

To do this, of course, you will need to save the link to the delegate in order to be able to de-register it. Sort of:

 EventHandler handler = delegate(System.Object o, System.EventArgs e) { System.Windows.Forms.MessageBox.Show("Click!"); }; Button.Click += handler; // ... program code Button.Click -= handler; 

Also see this question .

+9
source

If I remember correctly (and I can remember where I read it), built-in anonymous delegates cannot be deleted.

You need to assign a (static) delegate field.

 private static EventHandler<EventArgs> myHandler = (a,b) => { ... } myButton.Click += myhandler; ... myButton.Click -= myHandler; 
+2
source

All Articles