Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to unsubscribe events in my Form?

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 );
}
like image 365
Daniel Peñalba Avatar asked Dec 02 '22 22:12

Daniel Peñalba


1 Answers

Any object which subscribes to events from a longer-lived object should implement IDisposable and should unsubscribe those events when it is Disposed. 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.

like image 164
supercat Avatar answered Dec 18 '22 02:12

supercat