Asynchronous Image download on Windows Phone 7

When running your solution on local and setting the Source property of the System.Windows.Controls.Image it is not visually apparent that the Image may take some period of time to download simplifying the code the following the original image swap out whereby i was using an arbitrary Uri to an image in Azure Blob Storage that would change at a predefined interval.

imgContent.Source = new BitmapImage(new Uri(arbitraryImageUriThatKeepsChanging));

As soon as the image is available from Azure Blob Storage – or any other hosting provider for that matter if you are not using a CDN and are a long way from your host then or the image is of a large size then it is likely that as soon as the image is set the image content becomes empty until the image is downloaded – i found this to be 10 to 30 seconds over the slow bandwidth of my phone.  To have an empty Image control on the screen was not acceptable so the simple solution is to pull down the image asynchronously using a WebClient then once downloaded update the Image.Source as follows:

Starting the Async download of the image:

WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri(arbitraryImageUriThatKeepsChanging), wc);

Handling the completed download and updating the image source – note: have intentionally removed the MVVM implementation here to minimise code in post if using MVVM setup the binding on the Image.Source property to the model Source.

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
   if (e.Error == null && !e.Cancelled)
  {
      try
      {
         BitmapImage image = new BitmapImage();
         image.SetSource(e.Result);
         imgContent.Source = image;
      }
      catch (Exception ex)
      {
          //Exception handle appropriately for your app
      }
  }
  else
  {
      //Either cancelled or error handle appropriately for your app
  }

Async download of Images from Azure to windows phone.

Note: WebClient executes on the UI thread if you wish to do this on a background thread and then later update the UI you should use HttpWebRequest and then Dispatcher within your response to update the UI thread.

Note: It would be interesting to configure the Azure CDN to see the improved performance once the node is distributed from a CDN node that is geographically close.

Nick