Using async and await for Asynchronous calls in C# and VB

We are going to user asynchronous call to get length of web that we requested.

Download : C# or VB

Create new WPF project.



Add textbox and button.


Rename button to runAsyncButton and textbox to resultsWindow.
You can either do that  by adding x:Name property for each element, or click an element and get the properties and change name.
<Button x:Name="runAsyncButton" ... />
<TextBox x:Name="resultsWindow" .../>

Double click on button and click method is generated.

Xaml code for grid should looks similar:



Add this to your click method :
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
   resultsWindow.Clear();
   resultsWindow.Text += "Asynchronous call started";
   runAsyncButton.IsEnabled = false;
   runAsyncButton.Content = "Running...";
   await SumPageSizesAsync();
   runAsyncButton.IsEnabled = true;

   runAsyncButton.Content = "Run";
   resultsWindow.Text += "\n Asynchronous call finished";
}


As you can see method needs to have async keyword to perform as an asynchronous call.
Await keyword on SumPageSizesAsync method works in pair with async and tells method to wait before continuing if method is still being executed. 

We have to write SumPageSizesAsync method:


private async Task SumPageSizesAsync()
{
   List<string> urlList = SetUpURLList();

   foreach(var url in urlList)
   {
      // return contents as a byte array
      Byte[] urlContent = await GetURLContentsAsync(url);

      DisplayResults(url, urlContent);
   }

}


To populate list with url addresses:



private List<string> SetUpURLList()
{
   List<string> urls = new List<string>() { 

   "http://msdn.microsoft.com/library/windows/apps/br211380.aspx",
   "http://msdn.microsoft.com",
   "http://msdn.microsoft.com/en-us/library/hh290136.aspx"
};

return urls;
}


Now we have to write the core method - GetURLContentsAsync.


private async Task<byte> GetURLContentsAsync(string url)
{
   MemoryStream content = new MemoryStream();

   HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);

   // Send request and wait for response

   Task<webresponse> responseTask = webReq.GetResponseAsync();

   using (WebResponse response = await responseTask)
   {
      using (Stream responseStream = response.GetResponseStream())
      {
         await responseStream.CopyToAsync(content);
      }
   }
   return content.ToArray();
}


Final method is DisplayResults.

private void DisplayResults(string url, Byte[] content)
{    
   var bytes = content.Length;  
   resultsWindow.Text += string.Format("\n {0} {1}", url, bytes); 
} 


Run the program.




Comments