Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API: any downsides to asynchronous operations?

I'm setting up a Web API that will serve a client over our Intranet. For the sake of convenience for the developers working on the client, I am considering having the Web API adhere to an interface that will be shared with the client, something like what is shown below.

The purpose of using a shared interface mostly has to do with making changes to the Web API detectable by the client developers at compile time. Also, the client can leverage the interface to be used for wrappers around HttpClient instances that will be used to communicate with the Web API.

The client developers would like to use async and await throughout their implementation, and who am I to say "no"?

public interface IValueController
{
    Task<string> ReadAsync();
    string ReadSync();
}

[Route("api/v1/[controller]")]
public class ValueController : Controller, IValueController
{
    [HttpGet("async")]
    public Task<string> ReadAsync()
    {
        return Task.FromResult("async!");
    }

    [HttpGet("sync")]
    public string ReadSync()
    {
        return "sync!";
    }
}

I'm not all that interested in providing both synchronous and asynchronous methods - one of them will have to do. The question is: Is there any down-side to defining the Web API operations as asynchronous? If not, I'm going all-in!

-S

like image 216
Sigurd Garshol Avatar asked Mar 02 '26 15:03

Sigurd Garshol


1 Answers

When to use Async:

  1. Async API calls.
  2. Long Running database queries.
  3. Tasks that are CPU bound.
  4. When you need to achieve parallelism.

When not to use: While writing any quick running tasks or methods.

NOTE: Beware of deadlocks as the compiler allows you to write and successfully compile async code even without understanding it's basic concept.

like image 87
Jose Francis Avatar answered Mar 05 '26 05:03

Jose Francis