Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In vb.net, if I use AddHandler, Do I have to use RemoveHandler?

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!

like image 383
Summer Avatar asked Sep 15 '11 19:09

Summer


1 Answers

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.

like image 80
Reed Copsey Avatar answered Sep 25 '22 16:09

Reed Copsey