Why should I create async WebAPI operations instead of sync ones?

David Jiménez Martínez picture David Jiménez Martínez · Oct 2, 2014 · Viewed 83k times · Source

I have the following operation in a Web API I created:

// GET api/<controller>
[HttpGet]
[Route("pharmacies/{pharmacyId}/page/{page}/{filter?}")]
public CartTotalsDTO GetProductsWithHistory(Guid pharmacyId, int page, string filter = null ,[FromUri] bool refresh = false)
{
    return delegateHelper.GetProductsWithHistory(CustomerContext.Current.GetContactById(pharmacyId), refresh);
}

The call to this webservice is done through a Jquery Ajax call this way:

$.ajax({
      url: "/api/products/pharmacies/<%# Farmacia.PrimaryKeyId.Value.ToString() %>/page/" + vm.currentPage() + "/" + filter,
      type: "GET",
      dataType: "json",
      success: function (result) {
          vm.items([]);
          var data = result.Products;
          vm.totalUnits(result.TotalUnits);
      }          
  });

I've seen some developers that implement the previous operation this way:

// GET api/<controller>
[HttpGet]
[Route("pharmacies/{pharmacyId}/page/{page}/{filter?}")]
public async Task<CartTotalsDTO> GetProductsWithHistory(Guid pharmacyId, int page, string filter = null ,[FromUri] bool refresh = false)
{
    return await Task.Factory.StartNew(() => delegateHelper.GetProductsWithHistory(CustomerContext.Current.GetContactById(pharmacyId), refresh));
}

Gotta say, though, that GetProductsWithHistory() is a quite long operation. Given my problem and context, how will making the webAPI operation asynchronous benefit me?

Answer

i3arnon picture i3arnon · Oct 2, 2014

In your specific example the operation is not asynchronous at all so what you're doing is async over sync. You're just releasing one thread and blocking another. There's no reason to that, because all threads are thread pool threads (unlike in a GUI application).

In my discussion of “async over sync,” I strongly suggested that if you have an API which internally is implemented synchronously, you should not expose an asynchronous counterpart that simply wraps the synchronous method in Task.Run.

From Should I expose synchronous wrappers for asynchronous methods?

However when making WebAPI calls async where there's an actual asynchronous operation (usually I/O) instead of blocking a thread that sits and waits for a result the thread goes back to the thread pool and so able to perform some other operation. Over all that means that your application can do more with less resources and that improves scalability.