In vb.net, if I use AddHandler, do I need to use RemoveHandler?

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

I looked for several similar questions as follows, but I do not quite understand.

When and where to call RemoveHandler in VB.NET?

AddHandler / RemoveHandler does not correct

I thought that garbage collection in C # or vb.net would take care of unused objects. In addition, in the vb.net designer, it automatically creates a Dispose Sub. Therefore, I did not pay attention to the software release of the resource in general. Will I have a memory leak problem? Please bring me some links / documents 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!

+6
source share
1 answer

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

You do not have to do this.

You usually need to worry about calling RemoveHandler if your source object (the one with the event) is about to outlast your subscriber. If you work in the Form, the form that will be deleted will not allow the source to raise the event anymore, and both objects will be inaccessible and (ultimately) will receive garbage collection, so you will not have problems.

This problem arises more if you subscribe to an event on a durable object from any other object that will "go away" in front of the durable object. This can lead to a memory leak even with the garbage collector. In this case, you want to call RemoveHandler when you finish listening to the event. There is no single indication when this will happen, as it depends on the event in question and your application logic.

+10
source

Source: https://habr.com/ru/post/897418/


All Articles