I'm trying to understand how a Control
events are unsubscribed. Suppose I have a textbox and I have subscribed the TextChanged
event using the WinForms designer.
Is the TextChanged
event automatically unsubscribed in the Textbox
destructor, or must I explicitly unsunscribe to avoid memory leaks?
public void InitializeComponents()
{
...
this.emailTextBox.TextChanged += emailTextBox_TextChanged;
...
}
public override void Dispose()
{
if( disposing )
{
// DO I REALLY NEED THIS LINE?
this.emailTextBox.TextChanged -= emailTextBox_TextChanged;
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
Any object which subscribes to events from a longer-lived object should implement IDisposable
and should unsubscribe those events when it is Dispose
d. Conceptually, there's no reason why objects shouldn't unsubscribe from all events when they are disposed, since doing so would avoid problems if an object whose events one subscribed turned out to live longer than expected. Unfortunately, the event architecture in .NET provides no mechanism for conveniently ensuring that events get cleaned up when objects are disposed, and having code unsubscribe a bunch of events when an object is disposed may make it harder to make sure that the few events which really need to be cleaned up are among the ones that are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With