简体   繁体   中英

Where to unsubscribe events in a WinForms UserControl

Where would you unsubscribe events in a UserControl ? I subscribe to it in the Load event, like I have done in forms. And in forms I would usually unsubscribe in the Closing event, but I can't find anything similar in the UserControl ...

There are times when you would want to do this (for example, when using CAB ).
For completeness, the answer to your question is:

protected override void OnCreateControl()
{
    base.OnCreateControl();
    if(!DesignMode) //only time this.ParentForm should be null
        this.ParentForm.FormClosing += ParentForm_FormClosing;
}

private void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
{
    //Unregister events here
}

You could also override Dispose()

Is it necessary to unsubscribe at all? Is a reference to the user control held after it has been unloaded? If not, you don't need to worry about the event handlers because as soon as the user control is removed from memory, so are the event handlers. You don't leak references that way.

As others have said is there really a need to unsubscribe in your scenario?

If you really do need to unsubscribe however you do it exactly the reverse of subscribing:

UserControl1.Click -= new EventHandler(UserControl1_Click);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM