开发者

C# UI events unsubscription - necessary?

开发者 https://www.devze.com 2023-03-18 08:45 出处:网络
I know unsubscription from event IS necessary. My questions comes from the generated code: When you modify an ui from the VS editor, and add an event handler to a UI element (ex:

I know unsubscription from event IS necessary. My questions comes from the generated code: When you modify an ui from the VS editor, and add an event handler to a UI element (ex: private void BtnSampleClick(object sender, EventArgs e))

When creating this event handling, VS adds this code开发者_开发技巧 in the private void InitializeComponent() autogenerated code

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

Problem is that VS doesn't add the unsubscription (this.btnSample.Click -= new System.EventHandler(this.BtnSampleClick); ) automatically in the Dispose method of the form.

Normally we should add them there right? If not this will leak to memory leaks? Wanted to check if there was a reason why VS doesn't perform the unsubscription automatically. Maybe the form is correctly disposed even if we don't do it?

Thanks for helping me shred some light in this matter!


This isn't done, mainly because it's really not necessary in this case. The reason is that your Form is subscribing to events of objects which have a lifetime managed by the form. When the object (ie: the button) is unrooted from a GC perspective, the form will also be unrooted (and closed), so there is no chance of a memory leak. The GC in .NET is smart - circular references like this are not an issue.

Unsubscribing to events is still a good general practice, however. It becomes important if you subscribe to an event on an object which has a lifetime independent of the object which is making the subscription. This is especially true if the object with the event is much longer lived than the subscriber. This case is where event-caused memory leaks tend to occur. For example, if your Form subscribes to an event on a static instance, and forgets to unsubscribe, the form will never get garbage collected, since the delegate reference will keep it "rooted" via the event subscription.


Yes, it is a good practice to unsubscribe explicitly. Although they can cause memory leaks, as long as they are not holding any reference to unmanaged objects, GC can still correctly determine and cleanup in the managed world.


You need not to care about that. Dot.NET framework has a Garbage Collector (GC) that automatically dispose using its own principle (may be when there is no reference to the object left).

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

0

精彩评论

暂无评论...
验证码 换一张
取 消