What event signals that a UserControl is being destroyed?

C#.NetWinformsEventsAsynchronous

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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
    }

Solution 3 - C#

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.

Solution 4 - C#

Try this:

UserControl.Dispose();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGary McGillView Question on Stackoverflow
Solution 1 - C#StephanView Answer on Stackoverflow
Solution 2 - C#AvramView Answer on Stackoverflow
Solution 3 - C#slothView Answer on Stackoverflow
Solution 4 - C#GimhanView Answer on Stackoverflow