Real life example using async and await in an mvc application

The Quote of the day is: Marcus Tullius Cicero

The Author is: A room without books is like a body without a soul.

The weather is: Weather is Haifa Israel:25 Celsius

So what we have here?

At beginning of the page we see the result of two calls to two soap based web services

the first one is a web service that gets the quote from some famous another

and the second service gets the weather of an airport, given a country and a city

the code for all of this is:

  1. public async Task<ActionResult> AsyncAwaitExample()
  2.         {
  3.             AsyncAwaitExampleModel model = new AsyncAwaitExampleModel();
  4.             
  5.              Task<Quotes> retQuotesTask = getQuotesAsync();
  6.              Task<string> retWeatherTask = getWeatherAsync();
  7.              await Task.WhenAll(retQuotesTask, retWeatherTask);
  8.              model.Quotes = retQuotesTask.Result;
  9.              model.Weather = retWeatherTask.Result;
  10.              XDocument xdoc = XDocument.Parse(model.Weather);
  11.              model.Weather = xdoc.Descendants("Temperature").FirstOrDefault().Value;    
  12.              return View(model);
  13.         }
  14.  
  15.         private async Task<string> getWeatherAsync()
  16.         {
  17.             GlobalWeatherSoapClient globalWeather = new GlobalWeatherSoapClient("GlobalWeatherSoap");
  18.             return await globalWeather.GetWeatherAsync("Haifa","Israel");
  19.         }
  20.  
  21.         private async Task<Quotes> getQuotesAsync()
  22.         {
  23.             QuoteofTheDaySoapClient QuoteOfTheDay = new QuoteofTheDaySoapClient("QuoteofTheDaySoap");
  24.             return await QuoteOfTheDay.GetQuoteAsync();
  25.         }

First lets look at line 1 at a big advantage using async and await

the method asyncAwaitExample is itself an async method , this allows our server not to stuck while he waits to get the results from two of our services (line 7)

while the server is waiting for the answers in line 7 he can attend to other requests while checking if the results have came

The methods getWeatherAsync and getQuotesAsync are also async methods, each method has an await inside to wait for a result for each service

the combination of these methods and the await in line 7 allows the main method to wait call for both services together and wait for both of them to finish their calls

so here we found several advantages:

  1. The servers does not stuck and wait for both the calls to end
  2. We call the two services at the same time
  3. We wait for both the calls to end or for the longest of them