Home > OS >  Is there any benefit to have an async method call if this is the last call in the enclosing method?
Is there any benefit to have an async method call if this is the last call in the enclosing method?

Time:12-15

I have an API method like this:

[HttpGet("NumberOnStock")]
public async Task<int> NumberOnStock([FromQuery] Guid productId)
{
    return await _context.Products.Where(product => product.Id == productId).CountAsync();
}

Is there any benefit to have this method use CountAsync() instead of Count() if it is just the only and last call within NumberOnStock method?

CodePudding user response:

yes, assuming you are using a database with actual async support, using CountAsync() instead of Count() will free the thread to process other requests if run on a server. Or avoid blocking the UI thread if used in a UI application. This might not be super important for counting the number of rows, since this should return fairly quickly even using the blocking version in most cases. But using async-version of calls is generally a good practice.

If you are using CountAsync() you do not need to make use await or mark the method async. If you do not need to process the result in any way you can just return the task directly.

CodePudding user response:

By just returning the Task<int> rather than awaiting it you avoid allocating the state machine that goes with the await.

As for whether you should use Count or CountAsync, a call to Count will block the current thread whilst the count is performed, whereas the call to CountAsync will allow calling thread to me be made available to process other requests, improving overall application performance.

In summary, use CountAsync and don't bother with await:

[HttpGet("NumberOnStock")]
public Task<int> NumberOnStock([FromQuery] Guid productId)
{
    return _context.Products.Where(product => product.Id == productId).CountAsync();
}
  • Related