How to remove all event handlers from an event

后端 未结 18 1649
再見小時候
再見小時候 2020-11-22 01:20

To create a new event handler on a control you can do this

c.Click += new EventHandler(mainFormButton_Click);

or this

c.Cli         


        
18条回答
  •  失恋的感觉
    2020-11-22 01:43

    I'm actually using this method and it works perfectly. I was 'inspired' by the code written by Aeonhack here.

    Public Event MyEvent()
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        If MyEventEvent IsNot Nothing Then
            For Each d In MyEventEvent.GetInvocationList ' If this throws an exception, try using .ToArray
                RemoveHandler MyEvent, d
            Next
        End If
    End Sub
    

    The field MyEventEvent is hidden, but it does exist.

    Debugging, you can see how d.target is the object actually handling the event, and d.method its method. You only have to remove it.

    It works great. No more objects not being GC'ed because of the event handlers.

提交回复
热议问题