pdiddy
pdiddy

Reputation: 6297

Must I unsubscribe all event handlers?

From the Designer in VS let's say you double click on a button and it generates this Click event handler.

the subscription code is in the designer.cs.

I was wondering, in the dispose the Form MUST I unsubcribe the event ?

Also, all control that are in the form will it be disposed when the forms disposes? it actually call dispose on each control recursively?

Upvotes: 10

Views: 3475

Answers (3)

Pierre-Alain Vigeant
Pierre-Alain Vigeant

Reputation: 23083

On the question "will it actually call dispose on each control recursively?", the answer is yes.

A simple test can be done by putting a breakpoint in the Dispose method of a control.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        this.Controls.Add(new SuperButton());
    }
}

public class SuperButton : Button
{
    protected override void Dispose(bool disposing)
    {
        //Place breakpoint on the line below
        base.Dispose(disposing); 
    }
}

Upvotes: 2

saret
saret

Reputation: 2227

As long as the event handler code is the form itself, then you wouldn't need to unsubscribe the events - as there wouldn't be a dangling event handler to the controls as the form itself would be destructed

Upvotes: 1

Brian Genisio
Brian Genisio

Reputation: 48127

You don't need to unhook the event on Dispose if you are hooking your own event.

You only need to worry about it if you are hooking an event in another object. The reason for this is that event hooks keep a reference alive to the subscriber. If you fail to unhook, then you won't get garbage collected as long as the observable is still alive.

When you hook your own event, you have a reference to yourself, which is circular, therefore you don't need to worry about it.

I have come to support more loosely coupled event patterns for this reason. This is the #1 place for memory leaks in .Net. I prefer the Event Aggregator pattern (with weak events).

Upvotes: 15

Related Questions