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

倖福魔咒の 提交于 2020-01-02 02:47:06

问题


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:


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.



来源:https://stackoverflow.com/questions/7436024/in-vb-net-if-i-use-addhandler-do-i-have-to-use-removehandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!