Asynchronous Methods

ANB 181 Reputation points
2021-08-26T18:58:22.493+00:00

I am trying to convert my methods to asynchronous.
I have added async Task<IActionResult> and seems the methods work fine.
However, just it is enough to make them asynchronous? Wouldn't I need an "await" somewhere? but where ?

// CONTROLLER
public async Task<IActionResult> GetProducts()
{
try
{
return Ok(_productServices.GetAllProducts());
}
catch (Exception ex)
{
return StatusCode(500, "");
}
}

// SERVICES
public IEnumerable<ProductModel> GetAllProducts()
{
var products = List<ProductModel>() {
...
}
return products
}

Thank you,

Windows development | Windows API - Win32
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Sam of Simple Samples 5,571 Reputation points
    2021-08-26T19:19:59.933+00:00

    Yes you need an await somewhere. More important to that is it helps to understand that neither await nor async creates tasks, they support multitasking. You need to do something (else) that creates a task.

    Many developers prefer await and async but in my opinion they are unnecessarily complicated. You can do multitasking without them.

    0 comments No comments

  2. Xiaopo Yang - MSFT 12,736 Reputation points Microsoft External Staff
    2021-08-27T06:12:06.18+00:00

    If GetProducts don't call await, It‘s unnecessary to claim async.
    Only Task and async functions need to await. async and await.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.