Does WithEvents in Visual Basic retain their EventHandlers when changing an object reference?

Does WithEventsVisual Basic support its own EventHandlerwhen changing object references?

Say I declared a button by triggering events:

Private WithEvents _MyButton

Now I subscribe to the event handler:

Private Sub _MyButton_Click() Handles _MyButton.Click 
  ' Here I DoClick()
End Sub

Will the function be called DoClick()when I modify the instance of the button object as shown below?

_MyButton = New Button()
+5
source share
1 answer

I was curious, so I wrote a small console application to visualize what happens if you run this experiment with a timer:

Private WithEvents _t As New Timers.Timer With {.Enabled = True}
Private Sub _t_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles _t.Elapsed
    Console.WriteLine("tick")
End Sub

Sub Main()
    ' let it tick for 5 seconds
    Task.Delay(5000).Wait()

    ' destroy the current timer
    Console.WriteLine("destroying this timer")
    _t.Dispose()
    _t = Nothing

    ' add a little pause
    Task.Delay(1000).Wait()

    ' create a new timer
    Console.WriteLine("creating a new timer")
    _t = New Timers.Timer With {.Enabled = True}

    ' let it tick for 5 seconds
    Task.Delay(5000).Wait()

End Sub

, , , _t. , , , , Handles. , .

+3

All Articles