Async & Await in ASP.NET

0
824

In previous posts I showed how to use the TPL and Async await using a very simple WPF demo App.

In this Post I’m going to show an example using ASP.NET. It simply calls yahooapi to get a stock quote. First I’m going to install the HTTP client to fetch the content this yahoo API. I simply install Microsoft.Net.Http and I ready to use the HTTP client to perform web requests.

private const string YAHOO_REQUEST_URL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&env=store://datatables.org/alltableswithkeys";

public async Task<ActionResult> Index () {

  using (var client = new HttpClient ()) {
    var httpMessage = await client.GetAsync (YAHOO_REQUEST_URL).ConfigureAwait (false);

    var content = await httpMessage.Content.ReadAsStringAsync ().ConfigureAwait (false);

    return Content (content);
  }
}

Here I’m using get async by passing a yahoo request Uri as a parameter, it will return an HTTP response message after the asynchronous operation is completed. Since this is marked as async we know that we need to await this. We know that after the task is completed it’s going to return the result of that asynchronous operation. Now that I’m using sync I cannot simply return ActionResult. I need to wrap that in a task.

public async Task<ActionResult> Index()

Index here is now asynchronous and after the asynchronous operations within this method is done, it’s going to return an actual result. Now that I have the HTTP message, I can go ahead and fetch the body of that request.

var httpMessage = await client.GetAsync(YAHOO_REQUEST_URL).ConfigureAwait(false);

Getting the content means that I need to read this which is an asynchronous operation as well and Of course that also means that I need to await this as well because this is an asynchronous operation.

var content = await httpMessage.Content.ReadAsStringAsync().ConfigureAwait(false);

If I set a breakpoint at a few places as in the next Image, you’ll see that it’s first going to try to get request. And then it’s going to read the content and then it’s going to return the content back to the caller.

As a caller to the website or as a user of the website, it’s not really much of a difference. The biggest benefit of doing this is that I’m not blocking the thread from doing other work. That means that the ASP.NET application can process more things so it’s kind of a relief for the server.

You can notice I’m using:

ConfigureAwait(false)

In ASP.NET it has always been a good practice to configure your tasks with ConfigureAwait set to false. The reason for that is that it’s going to become a lot quicker because it’s going to pick one of the available threads in the ASP.NET thread pool and uses that to process the result.

LEAVE A REPLY

Please enter your comment!
Please enter your name here