Reputation: 6716
I got a little problem with adding and removing event handlers in Visual Basic.NET. While this is in general rather easy, I need to remove a inline event handler. Question is if and how this works.
AddHandler object.ConnectionSuccessful, Sub()
RemoveHandler object.ConnectionSuccessful, Me
End Sub
This is the way how I tried it, it does not work. Now the question is how do I remove this inline event handler again if not this way? I found some cruel methods to remove all event handlers from a object but this is not what I want to do. I only want to remove this one single specific event handler.
I am aware that those problem disappear if I just use a normal function and the AddressOf
operator. But in this case using the inline method is just more handy.
Anyone has a idea in this matter?
Upvotes: 1
Views: 699
Reputation: 4340
If you assign your lambda to a variable, then it is possible to do this (assuming this sort-of inline structure is close to what you want). Note that you have to Type the lambda, in this case as Action
in order to refer to itself from itself.
Module Module1
Event TestEvent As Action
Sub Main()
Dim TestLamba As Action = Sub()
Console.Write("Event!")
RemoveHandler TestEvent, TestLamba
End Sub
AddHandler TestEvent, TestLamba
RaiseEvent TestEvent()
RaiseEvent TestEvent()
Console.ReadKey()
End Sub
End Module
If you run this test console app above, you'll see that the event is fired twice, but "Event!" is only written to the console once.
Upvotes: 2