Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP - What happens if navigating away from page while async/await is running?

In a UWP app (or any C# app with a UI), what happens when an async method hasn't finished, but user navigates away from the page? My more specific concern is that when await is completed, the async method will continue and modify certain UI elements, but the user has navigated away from the page already.

| User enters Page
| Clicks on button
| Enters async method
| Hits await (returns to process events)
| User navigates away from Page
| awaited method completes
| ?

At this point, does the async method continue? If it does continue, and it tries to modify a UI element, will the app crash because the Page no longer exists?

like image 241
ShrimpCrackers Avatar asked Mar 09 '23 06:03

ShrimpCrackers


1 Answers

Yes. The async method will continue and your page will exist in memory. Your method can make modifications, but obviously they're unnecessary changes. Your app should not crash, unless you're trying to access elements that no longer exist. Such as Panel.Children[2].Opacity = 0 where Panel is now empty after being unloaded from screen. (just an example)

If your method runs for a long time, you should cancel the operations using a CancellationToken or a flag of some sort to allow you to "early-out" of the routine.

like image 126
Laith Avatar answered Apr 26 '23 22:04

Laith