Where i should use async await?
I have two methods. One of these will be used from "public async Task<int?> SomeASPNETControllerPostMethodAsync()".
Should i use await async everywhere or only in Controllers? Which one is the best for performance?
8 Replies
$rulesofasync
TLDR on
async
/await
:
* every .net API that is suffixed with Async
(eg: .Read()
and .ReadAsync()
) => use the Async
version
* if the API name ends with Async
=> await
it
* if the API returns a Task
=> await
it
* if you have to await
in a method:
* that method must have the async
keyword (you could even suffix your function name with Async
, up to you)
* if it was returning T
(eg:string
) => it should now return Task<T>
(eg: Task<string>
)
* APIs to ban and associated fix:
Speaking of your code in particular, the use of
.ContinueWith()
makes the code look like shit, as you can see
So just await what needs to be awaitedThank you!
As a side note, don't use
.AddAsync()
, .RemoveAsync()
and so on with EF
They're there for some edge cases
Since .Add()
, .Update()
and similar only touch the change tracker, not the db, they don't need to be asyncBut i must use SaveChangesAsync()?
Yes
Since that actually calls the database
Thanks