9

If I always need to call RemoveHandler after using AddHandler, where is the best place to do so?

I have searched several similar questions as follows, but I do not quite understand.

When and where to call the RemoveHandler in VB.NET?

AddHandler/RemoveHandler Not Disposing Correctly

I thought garbage collection in c# or vb.net will take care of unused objects. Also, in vb.net designer, it automatically generates Dispose Sub. So I did not pay attention to programally releasing resource at all. Will I have any memory leak problems? Please kindly provide me some links/documents for me to start learning.

Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
    Finally
        MyBase.Dispose(disposing)
    End Try
End Sub

Thanks a lot!

1
  • You'll have to post the context in which you are using AddHandler. Sep 15, 2011 at 19:03

1 Answer 1

13

If I always need to call RemoveHandler after using AddHandler, where is the best place to do so

You do not necessarily have to do this.

You only typically need to worry about calling RemoveHandler if your source object (the one with the event) is going to outlive your subscriber. If you're working within a Form, then the form getting disposed will prevent the source from raising the event anymore, and both objects will be out of scope and (eventually) get garbage collected, so you'll have no problem.

This issue arises more if you're subscribing to an event on a long lived object from some other object which will "go away" before the long lived object. This can cause a memory leak, even with the garbage collector. In that case, you'd want to call RemoveHandler when you were done listening to the event. There is no single guidance for when this should happen, though, as it depends on the event in question and your application logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.