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?
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.
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
}
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