AddHandler / RemoveHandler fixes incorrectly

Using the AddHandler method, if I never use RemoveHandler , will this lead to a memory leak in some conditions and situations? I am not so sure of the truth of this.

And are there other causes of memory leaks that are only available in VB, unlike C #?

+3
source share
2 answers

Well, usually this is not so .. but there is a possibility.
When you sign up for an event, you basically provide the delegate (pointer func if you want) with your method, the event publisher that holds onto it until you unsubscribe from the - = operator.

So, take, for example, the case when you create a child form, and the form subscribes to the Click button event on the form.

 button1.Click += new EventHandler(Form_Click_Handler); 

Now the button object will be attached to the link to the form. When the form is closed / set / set to zero, the form and button are no longer needed; memory fixed.

The problem arises when you have a global structure or object that has a longer lifespan. Assume that the Application object maintains a list of open child windows. Therefore, whenever a child form is created, the application object subscribes to the Form event so that it can follow it. In this case, even when the form is closed / located, the application object keeps it alive (the object that does not contain garbage contains a link to the form) and does not allow to restore memory. As you continue to create and close windows, you have a leak with your application, causing more and more memory. Therefore, you need to explicitly unsubscribe in order to remove the link to the form from the application.

 childForm.Event -= new EventHandler(Form_Handler) 

Therefore, it is recommended that you have a unsubscribe block (- =) that complements your subscribe subroutine (+ =) ... however you could do without it for stock scenarios.

+11
source

If object a is taken on object b of the object, then object b will not be assembled until object A.

An event signature is considered a reference to the publisherโ€™s object.

And yes, this happens in C #, I have nothing to do with the language.

0
source

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


All Articles