Home > Enterprise >  Should I await controller actions in ASP.NET?
Should I await controller actions in ASP.NET?

Time:09-10

I have two options for implementing controller actions in ASP.NET Web API:

By returning the task

public Task<Dto> Get()
{
    return QueryHandler.Execute();
}

or awaiting the task result

public async Task<Dto> Get()
{
    return await QueryHandler.Exectue();
}

I started using the first option because I thought it would create unnecessary overhead by awaiting. But later found that if there's a try/catch in a controller action the catch block will only execute if the result is awaited.

I guess I could keep all controller actions as one liners as a rule. But are there other downsides to return a task instead of awaiting? What is the best practice here?

CodePudding user response:

I started using the first option because I thought it would create unnecessary overhead by awaiting.

I've heard a quote somewhere about premature optimization... ;)

But seriously, I suspect the savings here would literally be immeasurably small, completely swamped by something as tiny as an Ethernet packet collision along the way.

But later found that if there's a try/catch in a controller action the catch block will only execute if the result is awaited.

Yes.

In general, I recommend keeping the async/await for reasons described on my blog. All of these essentially boil down to "it's too easy to get wrong". One of the pitfalls being catching exceptions.

  • Related