Using Async and Await

Duration

15 minutes

Goals

The primary goal of this lab is to modify an existing application to use the event-based async pattern to download search results from a web service.

Required assets

The provided Exercise 1 folder contains a subfolder named Start with a solution you will use as starting point. There is also a Completed folder with a solution you can use to check your work. Please make sure you have these folders before you begin.

Challenge

Update an existing application to use the event-based async pattern when searching for movies.

  1. Examine the start solution.
  2. Add a new method to MovieApi.cs called SearchAsync that uses WebClient's DownloadStringAsync method and the DownloadStringCompleted event.
  3. In MovieApi.cs, create a public Action named SearchComplete and invoke it when the search completes, passing in the movie data.
  4. In SearchPage.xaml.cs, update the OnSearch method to use the new SearchAsync method and SearchComplete action.

Steps

Examine the Start Solution

  1. Open the MediaPhone shared project.
  2. Inspect SearchPage.xaml; it displays a SearchBar and a ListView.
  3. Open the Data folder in the solution explorer. The code in MovieApi.cs is used to query the iTunes movie database.
  4. SearchResult.cs holds a model object class to hold the returned data.
  5. Run the application and try searching for a movie.
  6. Perform a search using a keyword that will return multiple results (try captain). Try to interact with the UI before the search results are returned? What happened?

Add an Asynchronous Search Method

  1. Open MovieApi.cs.
  2. Create a new void method named SearchAsync that accepts a single string parameter named text.
  3. Copy the null check code, the creation of the local query string and the creation of the WebClient from the old Search method.

    Show Code

  4. Instead of calling the WebClient's DownloadString method, subscribe to the DownloadStringCompleted EventHandler. You may use any subscription method you prefer; the completed solution uses a lambda expression.
  5. Within the handler, check the DownloadStringCompletedEventArgs's Error property for null.
  6. If Error is null, we can assume the download completed successfully. Save the DownloadStringCompletedEventArgs's Result property to a local string variable named resultText.
  7. Parse the resultText using the static JsonConvert.DeserializeObject method and save to local variable named results.
  8. Call the WebClient wc's DownloadStringAsync method. For the parameter, create a new Uri passing query into the constructor of the Uri.
  9. Show Code

Provide the Search Results

We'll create a public action that will provide the deserialized results to a subscriber when the results are ready.

  1. In MovieApi.cs, create a public Action that accepts an IEnumerable of SearchItems and an Exception named SearchComplete.
  2. Add the event keyword before the Action declaration to limit its accessibility.
  3. The deserialized results variable contains a property that is also named results which is a List of SearchItems. When invoking the Action, pass in results.results as the first parameter and null for 2nd Exception parameter.
  4. If e.Error is not null, invoke the SearchComplete Action passing in null for the first parameter and the error for the second parameter.
  5. Show Code

Invoke the Async Search method

  1. Open SearchPage.xaml.cs.
  2. In the OnSearch method, delete the try, catch, and finally blocks.
  3. Show Code

  4. Create a local instance of MovieApi named api. Subscribe to its SearchComplete event that we created in the last step.
  5. In the handler, check if the Exception exists, and if so return.
  6. If the Exception is null, use a foreach loop to add each item from the passed in IEnumerable of SearchItems to the ListView's data source named Data.
  7. Set the searchProgress's IsRunning property to null to hide the activity indicator.
  8. After the handler, call api's SearchAsync method, passing in the search terms text from the searchBar.
  9. Run the application. Notice that the ActivityIndicator is now visible during searches.
  10. Show Code

Summary

In this exercise, you updated an existing application to use the event-based async pattern to query a web service for search results. This allowed the UI to remain responsive while waiting for the results from the web service.

Go Back