Windows 8 store apps using async and await

Using async and await in windows 8 store apps bit tricky sometimes. Here I’m listing below some of the do’s and don’ts when working with async and await.

1) Always use void type for  top level async method. Don’t use return type Task for top level async method i,e. the method called by some app handler  for example click, onnavigatedfrom, onloaded etc.  This may not be same for console apps, where the top level method should always return Task in order to put wait instruction from Main method. Using same Task.Wait() in store apps blocks the UI thread and enters into deadlock.

   void Page_Loaded(object sender, RoutedEventArgs e)
        {
              TopLevelMethod();
	}
  
public static async void TopLevelMethod()
{
     var response = await PostAsync(url, content);
}

Without any top level async method

 async void Button1_Click( object sender, RoutedEventArgs e)
{
 var response = await PostAsync(url, content);
}

2) To update UI before and/or after async operation, include update code in the async method but not in its caller for example showing/hiding progress ring or some alert after receiving response etc.

3) If your top level async method is called by timer event or some other scheduler  event and it is accessing any UI related stuff, then use Dispatcher.RunAsync to run that method uses same thread context.

Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, TopLevelMethod);

4)  Utilize features of newly introduced simplified HttpClient class for all asynchronous get and post methods. You can use httpwebrequest async methods but same can be achieved with lesser code using HttpClient.

HttpClient

Example using httpclient post async (fewer lines )

    
public static async Task PostAsync(string url, string postContent)
        {
            using (var httpClient = new HttpClient())
            {
                var httpContent = new StringContent(postContent, Encoding.UTF8, "text/xml");

                using (var response = await httpClient.PostAsync(url, httpContent))
                {
                    response.EnsureSuccessStatusCode();

                    string content = await response.Content.ReadAsStringAsync();

                    return content;
                }
            }
        }

5)  Use always async and await for all anything that reads/writes from/to media(disk i/o etc.).

Example:

 
var file = await Package.Current.InstalledLocation.GetFileAsync("Data\\Groups.txt");
var result = await  FileIO.ReadTextAsync(file);
var xml = await reader.ReadToEndAsync()

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.