Search code examples
async-awaitasp.net-core-webapiasp.net-core-2.1

Does async provide performance improvements in this scenario? (.Net Core 2.1 Web API)


I have a .Net Core 2.1 Web API. Many of my controller actions are not async, and I was thinking about making them async. But I was wondering if it would have any performance improvement at all in at least simple scenarios? Take a very basic action as an example:

// GET: api/People/5
[HttpGet("id")]
public Person GetPerson([FromRoute] int id)
{
    return _context.People.FirstOrDefault(p => p.Id == id);
}

If I were to convert this to:

// GET: api/People/5
[HttpGet("id")]
public async Task<Person> GetPerson([FromRoute] int id)
{
    return await _context.People.FirstOrDefaultAsync(p => p.Id == id);
}

Surely, at least in this very basic example, the two actions would execute in the same period of time? I mean, even if there are two simultaneous calls to the non-async action method, IIS/Kestrel would take on the task of creating a second instance of it to allow both to execute simultaneously? I mean, it's not like because one client has called this API endpoint, now all other clients must wait for it to complete before they can be served, because it's not async?


Solution

  • https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

    Asynchrony is essential for activities that are potentially blocking, such as web access. Access to a web resource sometimes is slow or delayed. If such an activity is blocked in a synchronous process, the entire application must wait. In an asynchronous process, the application can continue with other work that doesn't depend on the web resource until the potentially blocking task finishes.

    with async/await you free your application for manage other work