views:

793

answers:

3

Suppose I have a form opened via the .ShowDialog() method.

At some point I attach some event handlers to some controls on the form.

e.g.

// Attach radio button event handlers.
this.rbLevel1.Click += new EventHandler(this.RadioButton_CheckedChanged);
this.rbLevel2.Click += new EventHandler(this.RadioButton_CheckedChanged);
this.rbLevel3.Click += new EventHandler(this.RadioButton_CheckedChanged);

When the form closes, I need to remove these handlers, right?

At present, I am doing this when the FormClosing event is fired.

e.g.

private void Foo_FormClosing(object sender, FormClosingEventArgs e)
{
    // Detach radio button event handlers.
    this.rbLevel1.Click -= new EventHandler(this.RadioButton_CheckedChanged);
    this.rbLevel2.Click -= new EventHandler(this.RadioButton_CheckedChanged);
    this.rbLevel3.Click -= new EventHandler(this.RadioButton_CheckedChanged);
}

However, I have seen some examples where handlers are removed in the Dispose() method.

Is there a 'best-practice' way of doing this?

(Using C#, Winforms, .NET 2.0)

Thanks.

+7  A: 

You don't need to remove the handlers in this case because neither the form nor its buttons are referenced by code external to the form, and the entire object graph will therefore be garbage collected.

Ben M
Right, so because the form is disposed, all the controls on it are too, which means there are no possible links for the event handlers? I always thought that if I created something, I should clean up after it too.
Andy
That's right. If you wanted collection of an object where one of its methods was the target of events in another object that was sticking around, then you'd have to remove the handlers. In this case, though, the objects (form + buttons) only reference each other.
Ben M
Thanks Ben, understood.
Andy
A: 

No, you don't need to remove the event handlers from controls on the form that is closing. They will all be disposed together.

You're probably thinking of web pages where removing event handlers is needed to avoid memory leaks in the browser.

dthorpe
Server side event handlers cause memory leaks in the browser?
Chris Taylor
No, browser side event handlers cause memory leaks in the browser. In older browsers, if you leave page load events etc hooked up, when the URL changes to a different page, the page load event is still hooked up to the old page. Thus, memory leak.
dthorpe
A: 

When you add an event handler, all you're doing is adding little bit of javascript to what's being sent back to the user.

When you get a FormClosing event, you're not resending the page, so you don't need to do this.

egrunin
This question is about WinForms, not ASP.net.
adrianbanks
Ahh, missed that.
egrunin