21

How do I use RemoveHandler with anonymous methods?

This is how I add a handler for MyEvent event of the class MyClass:

AddHandler MyClass.MyEvent, Sub()
                                '...
                            End Sub

How do I then use RemoveHandler to remove the handler for the MyEvent event?

Sreenikethan I
  • 319
  • 5
  • 17
acermate433s
  • 2,514
  • 4
  • 24
  • 32

1 Answers1

31

In general, if you need to unsubscribe from the event, I would recommend not using a lambda like this, and instead use a standard method.

That being said, you can still use the anonymous method, but you need to store a reference to it for the unsubscription. If you must unsubscribe an anonymous method, at a minimum, you should store the delegate in a variable to remove it later:

Dim subscription = Sub()
                            ' ...
                   End Sub

AddHandler MyClass.MyEvent, subscription

' Later   
RemoveHandler MyClass.MyEvent, subscription
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    Makes senses. If that's the case there's no point using anonymous methods when I have to remove it at a later time. – acermate433s Sep 16 '11 at 15:56
  • 1
    @acermate433s: True, which is why I suggested using a standard method. The one advantage of a lambda, thoguh, is you can close over local variables instead of promoting them to class level, which can be useful at times... – Reed Copsey Sep 16 '11 at 16:04