Sigurd Garshol
Sigurd Garshol

Reputation: 1544

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

Upvotes: 3

Views: 395

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 457217

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.

These days, it's more common to auto-generate an API description (e.g., Swagger), and then auto-generate clients from that (which can be .NET or other languages). Not only does this approach allow multiple clients (e.g., one Swagger client is HTML documentation for your APIs, complete with examples and the ability to invoke them right from the website), but it also handles the synchronous/asynchronous translation for you without requiring any kind of "async signature but really it's sync" code.

That said, if you wanted to implement asynchronous methods synchronously, there's nothing that would prevent it. The only gotcha I can think of is that if you're on full ASP.NET, then asynchronous actions cannot be child actions. This restriction no longer exists on ASP.NET Core.

Upvotes: 0

Jose Francis
Jose Francis

Reputation: 960

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.

Upvotes: 1

Related Questions