No C # UI Event Subscription Required?

I know that you need to unsubscribe from an event. My questions come from the generated code: When you change the ui from the VS editor and add an event handler to the user interface element (for example: private void BtnSampleClick(object sender, EventArgs e) )

When creating this event handling, VS adds this code to the private void InitializeComponent() code with auto-generated

 this.btnSample.Click += new System.EventHandler(this.BtnSampleClick); 

The problem is that VS does not add the unsubscribe ( this.btnSample.Click -= new System.EventHandler(this.BtnSampleClick); ) automatically in the form's Dispose method.

Usually should we add them there right? If this is not a memory leak? You need to check if there was a reason why VS was not automatically unsubscribing. Maybe the form is configured correctly, even if we do not?

Thank you for helping me kindle the light in this matter!

+4
source share
3 answers

This is not done, mainly because in this case it really is not necessary. The reason is because your form subscribes to events of objects that have a whole life controlled by the form. When an object (i.e., Button) is not removed from the GC perspective, the form will also be disabled (and closed), so there is no possibility of a memory leak. GC in .NET is smart - circular links like this are not a problem.

However, unsubscribing from events is still a good general practice. This becomes important if you subscribe to an event on an object that has a lifetime, regardless of the object that does the subscription. This is especially true if the object with the event is much longer than the subscriber. In this case, memory leaks caused by events. For example, if your form subscribes to an event on a static instance and forgets to unsubscribe, the form will never receive garbage collection, since the link to the delegate will support it β€œin the root” through event subscription.

+6
source

Yes, it’s right to unsubscribe. Although they can cause a memory leak if they do not contain references to unmanaged objects, the GC can still correctly identify and clean up in a controlled world.

+1
source

You do not need to worry about that. The Dot.NET Framework has a garbage collector (GC) that automatically disposes of its own principle (maybe when there is no reference to an object).

This does not mean that you will never need to call the Dispose function, in some case you intentionally call the Dispose () method so that the memory does not end, or when we work with the native dll / Marshal class

0
source

All Articles