Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task without async/await in controller action method

So I have a question about Task and async/await operation.

I have a method like this:

public Task<IActionResult> PostCompleteFormModel(string name, [FromBody]IndicatorFormApi apiModel, Guid participantId, [FromServices] IChallengeCycleService challengeCycleService)
{
    return Post(name, apiModel.ToSubmitApi(), participantId, challengeCycleService);
}

in a controller.

And as you can see it is without async/await.

But is it not better to do it like this:

public async Task<IActionResult> PostCompleteFormModel(string name, [FromBody]IndicatorFormApi apiModel, Guid participantId, [FromServices] IChallengeCycleService challengeCycleService)
{
    return await Post(name, apiModel.ToSubmitApi(), participantId, challengeCycleService);
}

So with the async/await keywords?

Or doesn't make it a differ?

Thank you


1 Answers

Both methods are asynchronous, but they have slightly different semantics. Specifically, they will behave differently if ToSubmitApi throws an exception.

The async keyword creates a state machine, which is responsible for managing the returned Task. If the code in an async method throws an exception, then the async state machine captures that exception and places it on the returned Task. This is the expected semantics for a method that returns Task.

Without the async keyword, the method would call ToSubmitApi and then call Post and return the Task returned from Post. So if ToSubmitApi threw an exception, that exception would be raised directly to the caller rather than being placed on the returned Task. These semantics are not expected.

As a general rule, I recommend keeping the async and await keywords unless the method is trivial and will not throw an exception. E.g., overloads that essentially supply default argument values. In this specific case, ToSubmitApi is a separate method that could possibly throw (or could be changed in the future to throw), so I recommend keeping the async and await keywords.

like image 51
Stephen Cleary Avatar answered Sep 05 '25 12:09

Stephen Cleary