Why would you ever use async void

Suppose you have a method that uses async task mechanism. Simplest example would be say displaying MessageDialog. Example I will use is using Launcher class to launch browser with a Url.

string BingMapsUri = String.Format("http://www.bing.com/maps/default.aspx?cp={0}~{1}&lvl=18&style=u", latitude, longitute);
 Uri uri = new Uri(BingMapsUri, UriKind.Absolute);
 await Launcher.LaunchUriAsync(uri);

this will launch the default browser with the uri above. Suppose you had an appbar button and you wanted to use click or tapped event to execute above code. The click event handler by default looks like this

private void btnViewOnMap_Click(object sender, RoutedEventArgs e)
{
}

one way would be to declare btnViewOnMap_Click to return Task and declare it async.

private async Task btnViewOnMap_Click(object sender, RoutedEventArgs e)
{
}

However event handlers do not like this and will refuse to work. In my early Win8 dev days I was stumped by this… what the heck was I supposed to do ? The answer was simple.

private async void btnViewOnMap_Click(object sender, RoutedEventArgs e)
{
}

just add async declaration to the event handler. this just informs the framework that this method will make and await async tasks. the event handler would look like this

private async void btnViewOnMap_Click(object sender, RoutedEventArgs e)
{
    string BingMapsUri = String.Format("http://www.bing.com/maps/default.aspx?cp={0}~{1}&lvl=18&style=u", latitude, longitute);
    Uri uri = new Uri(BingMapsUri, UriKind.Absolute);
    await Launcher.LaunchUriAsync(uri);
}

That is the only use of async void. In all other circumstances, you should use async Task

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s