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.