What event signals that a UserControl is being des

2020-05-21 08:06发布

问题:

I have a UserControl-derived control the displays some information fetched from a web server. I'm currently in the process of making the initialization of the control asyncronous, to improve responsiveness.

In my Load event handler, I'm creating a CancellationTokenSource, and using the associated Token in the various async calls.

I now want to ensure that if the user closes the form before the async operation completes, the operation will be cancelled. In other words, I want to call Cancel on the token.

I'm trying to figure out where to do this. If there was an Unload event that I could trap, then that would be perfect - but there isn't. In fact, I can't find any event that looks suitable.

I could trap the close event for the containing Form, but I really wanted to keep everything local to my UserControl.

Suggestions?

回答1:

I suggest the Control::HandleDestroyed event. It is raised, when the underlying HWnd is destroyed (which usually happens, when the parent form is closed). To handle it in your own UserControl, you should override OnHandleDestroyed.

You have full access to the Control's properties at this moment, because it is not yet disposed of.



回答2:

Another solution

    protected override void OnParentChanged(EventArgs e)
    {
        base.OnParentChanged(e);

        if (parentForm != null)
        {
            parentForm.Closing -= parentForm_Closing;
        }
        parentForm = FindForm();

        if (parentForm != null)
            parentForm.Closing += parentForm_Closing;
    }

    void parentForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        parentForm.Closing -= parentForm_Closing;
        parentForm = null;
        //closing code
    }


回答3:

Why not just use the Disposed event?

When a form is closing, it will call Dispose on itself and all child controls will be disposed recursively as well.



回答4:

Try this:

UserControl.Dispose();