UWP. What happens if you navigate away from the page while async / await is running?

In a UWP app (or any C # app with a UI), what happens when the async method hasn't finished yet, but the user navigates away from the page? My more specific problem is that when the wait is complete, the async method will go on and change some UI elements, but the user has already moved further away from the page.

| User enters page | Click on the button
| Enters an asynchronous method
| Hits are waiting (going back to processes)
| User moves away from page
| expected method completed
|

At this point, does the async method continue? If it continues and tries to change the UI element, will the application crash because the page no longer exists?

+3


source to share


2 answers


Yes. The async method will continue and your page will exist in memory. Your method may be making changes, but obviously these are unnecessary changes. Your application shouldn't crash unless you're trying to access items that no longer exist. For example, Panel.Children[2].Opacity = 0

where is Panel

now empty after being unloaded from the screen. (just an example)



If your method has been working for a long time, you must undo the operations with CancellationToken

or some flag so that you can "release" the procedure.

+6


source


It depends on what you mean by navigation . If this means that you close the form neatly and thus destroy all of your one-off elements, the form will still exist in memory, because your thread context still contains references to objects in your form.

However, most System.Windows.Forms.Control

objects throw exceptions when you access them after they have been deleted.

Example:

private void OnButtonShowMyAsyncForm_Clicked(objece sender, Eventargs e)
{
    using (var form = new MyAsyncForm(...))
    {
        var dlgResult = form.ShowDialog(this);
        ProcessResult(dlgResult);
    }
    // here your form and all controls on it are disposed, but not collected yet
    // if an async thread does something with any of the controls
    // like enable a button, an exception is thrown.
}

      



So, it would be better if the Form.Closing event handler checks that some process is still running and either cancel the close or wait for the process to finish.

private void OnFormClosing(object sender, CancelEventArgs e)
{
    bool asyncProcessRunning = this.MyTask != null && !this.MyTaks.IsCompleted;
    if (processRunning)
    {
        MessageBox.Show(this, "Can't close. Task still running", this.Text, 
            MessageBoxButton.OK,
            MessageBoxIcon.Warning);
        e.Cancel = true;
    }
 }

      

An even easier way is to notify the operator and give him the opportunity to

  • Redo: the task may have been completed by now,
  • Ignore: Do not wait for the task to complete, but take precautions if no problem occurs when the task completes.
  • Cancel: undo closing a form
0


source







All Articles