Cencek
Cencek

Reputation: 33

What happens when I try to remove handler that was never added?

I have an event handler. I add an event 5 secs after start to it like this:

AddHandler MyHandler, AddressOf DoStuff

Now when disposing the whole form, I need to

Private Sub Unsubscribe()
     RemoveHandler MyHandler, AddressOf DoStuff
End Sub

What if I close the form earlier than 5 secs after start? Is it a problem when I try to RemoveHandler that was never added? Is it the same in c# with += and -=?

Upvotes: 0

Views: 732

Answers (2)

Nostromo
Nostromo

Reputation: 1264

In my opinion it is absolutely fine to call RemoveHandler, regardless of calling AddHandler before.

But if you really like to please your colleague for the sake of it, then you could use the following check. I created a WinForms form with just a button called "Button1" on it. Here's the code behind:

Public Event Test As EventHandler

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'AddHandler Me.Test, Function(sender2 As Object, e2 As EventArgs)
    '                        Return Nothing
    '                    End Function

    If Me.TestEvent Is Nothing Then
        MsgBox("No event handler attached, RemoveHandler not necessary")
    Else
        MsgBox(String.Format("{0} event handler(s) attached, RemoveHandler for all subscriptions necessary", Me.TestEvent.GetInvocationList.Count))
    End If
End Sub

Microsoft creates an EventHandler object for every Event that is subscribed to, and names it like the event followed by "Event" (my event is called "Test" so the EventHandler is called "TestEvent").

So, if the EventHandler is Nothing, the event hasn't been subscribed to yet, and if it is not Nothing, you can even check how often it is subscribed to.

Upvotes: 0

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239804

At the end of the day, this winds up working with MulticastDelegates, and the action of RemoveHandler (VB) or -= (C#) is to call RemoveImpl, which returns:

If value is found in the invocation list for this instance, then a new Delegate without value in its invocation list; otherwise, this instance with its original invocation list.

So its fine.

(This ignores custom event accessors, but any implementation of those should try to follow the same pattern)

Upvotes: 5

Related Questions