Developing for Modern Windows

Tips, tricks, and guides for developing on modern Windows platforms

Async OnNavigatedTo in WinRT Universal Apps

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)
{
navigationHelper.OnNavigatedTo(e);
await DoSomethingAsync();
}

Now you can start a network data download or read files from disk asynchronously when your page launches.

No Async in Constructors

Don’t call async methods synchronously from the page’s constructor. Visual Studio gives you a warning if you do this:

public class MyClass()
{
public MyClass()
{
DoSomethingAsync();
}

async Task DoSomethingAsync()
{
// do asynchronous activity here
}
}

“Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the ‘await’ operator to the result of the call.”

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.

Links

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.

Tags: ,

Leave a Reply

Your email address will not be published.