Tips, tricks, and guides for developing on modern Windows platforms
By default, a page’s
OnNavigatedTo() method page is not asynchronous, but you can add the async keyword:
protected async override void OnNavigatedTo(NavigationEventArgs e)
Now you can start a network data download or read files from disk asynchronously when your page launches.
Don’t call async methods synchronously from the page’s constructor. Visual Studio gives you a warning if you do this:
public class MyClass()
async Task DoSomethingAsync()
// do asynchronous activity here
The async method will be called asynchronously, but your code doesn’t know when it finishes. This has several negative implications (see the links below for explanations).
You can’t make a constructor async (in a nutshell this is because a constructor needs to construct and return something right away, not ‘sometime later’). See the links below for your options.
When you need to initiate async tasks from a constructor (in a class that is not a page with an
OnNavigatedTo() to piggyback on), this excellent article by Stephen Cleary gives you a few choices.
For some great async-related videos, see Lucian Wischik’s async tips on Channel 9. Lucian explains very clearly how to use async correctly, and why you should do so.