Reputation: 9396
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();
Upvotes: 3
Views: 1099
Reputation: 73502
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.
Upvotes: 3
Reputation: 99979
Calling Dispose()
does not explicitly remove event handlers, but it does result in those events no longer being sent. When the garbage collector reclaims the memory from button
, the even registrations will be finally removed.
The more important situation to consider is when button
is listing for events from other objects:
var button = new Button();
otherObject.SomeEvent += button.HandleSomeEvent;
// ...
button.Dispose();
In this case, the registered event handler can actually prevent button
from getting garbage collected. If this situation applies to your code, you'll need to either remove the relevant event listeners in the Dispose()
method, or use a weak event listener pattern to allow the garbage collector to clean up those handlers.
Upvotes: 5