mike
mike

Reputation: 1734

Must a form remove all event handlers when closing/disposing?

I stumbled over this code snippet at How to remove all event handlers from a control :

void OnFormClosing(object sender, FormClosingEventArgs e)
{
    foreach(Delegate d in FindClicked.GetInvocationList())
    {
        FindClicked -= (FindClickedHandler)d;
    }
}

My question is: assuming that the form is about to be disposed (after being closed), would the snippet be required or would FindClicked and all references to event handler delegates simply go down with the form when it is GC´ed (which the referenced event handlers shouldn't cause any problems with)?

Upvotes: 1

Views: 1592

Answers (1)

Thomas English
Thomas English

Reputation: 231

Documentation suggests that you should remove all event handlers when disposing:

In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object.

You can also check out this other answer, which might be useful: Does `Control.Dispose()` remove all event registrations?

Upvotes: 2

Related Questions