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

1

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!

Epistle answered 15/9, 2011 at 19:1 Comment(1)
You'll have to post the context in which you are using AddHandler.Iodoform
T
14

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.

Tisbe answered 15/9, 2011 at 19:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.