Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET RemoveHandler & Anonymous Methods

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?

like image 372
acermate433s Avatar asked Sep 16 '11 15:09

acermate433s


1 Answers

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 
like image 167
Reed Copsey Avatar answered Sep 19 '22 06:09

Reed Copsey