I recently began working in a new company. They have an ASP.NET Core 3.1 application hosted in IIS, which takes API calls from an angular app. They used async/await literally "everywhere": Methods in the ASP.NET controllers have signatures like public async Task<IActionResult> Foo(), all DB queries are made async, all calls to external APIs anyways (which I kind of understand).
So instead of simply
[HttpPost("api/ignorableDepartment")]
public IActionResult Add([FromBody] AddIgnorableDepartmentRequest model)
{
return _ignorableGroupManager
.Add(model)
.ToResult();
}
the code now reads
[HttpPost("api/ignorableDepartment")]
public async Task<IActionResult> AddAsync([FromBody] AddIgnorableDepartmentRequest model)
{
return await _ignorableGroupManager
.AddAsync(model)
.ToResultAsync()
.ConfigureAwait(false);
}
This application is only used by 1-2 people at the same time, and the calls in the method above would take 1ms at most.
In the past I would only use async/await if the processing is expected to last like 1 second or more, and in all other cases, I would just rely on IIS to take care of spreading multiple requests across threads/cores.
Did I just miss something in the past years, and this is the new way to develop? Or is that just overkill?
Updated information to answer questions in the comments
AddAsyncadds themodelto the database. So I guess it's okToResultAsync()looks as follows (which makes no sense IMHO, since the controller method returns aTask<IActionResult>anyway. It also doesn't parse the passed information in any way, which aTo...method would indicate)
public static async Task<IActionResult> ToResultAsync(this Task task)
{
if (task == null)
{
throw new ArgumentNullException(nameof(task));
}
await task.ConfigureAwait(false);
return new OkObjectResult(ResultResponse.Success);
}
_ignorableGroupManager.AddAsync(model)do? It's hard to tell whatAddAsyncdoes. If it's saving to db, then it's fine. by the way, async does not mean use a new thread.ConfigureAwait(false). ASP.NET Core doesn't have a synchronization context that could be blocked.AddAsync(model).ToResultAsync()I don't quite understand this notation. Methods ending withAsyncshould return aTaskand be awaited, not chain-called.async/awaitfor IO-bound operations like working with a database or the file system. However, don't fall into the trap of doing a kind of fake asyncawait Task.Run(() => //CPU-bound stuff)in the case of a server-side app. It can work well for UI apps like WPF cause the CPU-bound operation won't freeze it, but be careful when using that in the server-side app. Also, I think that it's not overkill, there's not so much overhead, just addingTaskto signature and decorating it withasyncand findingasyncoverloads of methods you use.