Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I add async/await to a single-line function or not?

Should I add async/await to a single-line function like:

public async Task<T> GetFoo()
{
    return await HandleAsync<T>(....);
}

Or is this unneeded overhead if the parameter does not need an asynchron call and I can simple write:

public Task<T> GetFoo()
{
    return HandleAsync<T>(....);
}
like image 426
Horcrux7 Avatar asked Oct 17 '17 08:10

Horcrux7


People also ask

When should you use async await?

Async/Await makes it easier to write promises. The keyword 'async' before a function makes the function return a promise, always. And the keyword await is used inside async functions, which makes the program wait until the Promise resolves.

Is it OK to not await async?

Yes. If you don't need to wait, don't wait.

Should you await all async functions?

There's no specific need to mark a function async unless you specifically need one of the benefits of an async function such as the ability to use await inside that function or the automatic error handling it provides.

Does async await improve performance?

C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.


1 Answers

Use second overload, because async methods are converted into astate machine behind the scenes (an extra class) to handle asynchronous operation with awaits.

So first method adds unnecessary overhead. Second overload simply returns a task that you can still await on.

Im not sure about how exception handling wold change here but i think it doesnt change.

like image 183
M.kazem Akhgary Avatar answered Oct 21 '22 22:10

M.kazem Akhgary