Search code examples
.netgarbage-collectiondispose

Does `Control.Dispose()` remove all event registrations?


When I call Dispose() on a System.Windows.Forms.Control, does it automatically remove all event registrations?

So for example, is the following sufficient:

var button = new Button();
button.Click += someObject.clickHandler;
// ...
button.Dispose();

Or do I need to unregister the event handler explicitly, like this:

var button = new Button();
button.Click += someObject.clickHandler;
// ...
button.Click -= someObject.clickHandler;
button.Dispose();

Solution

  • Nope, It doesn't. You ought to remove the handlers yourself. Simple test can prove that.

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
    
        var button = new Button();
        button.Click += button_Click;
    
        //Some code
        button.Dispose();
        button.PerformClick();//Simulate a click event
    }
    
    void button_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Oops! Still alive?");
    }
    

    Run the above code, You'll see MessageBox popping up saying "Oops! Still alive?" which means handlers are not removed even when we Dispose the Control.

    Refer Marc's answer here to see how this can affect Garbage collection.