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?
No description
8 Replies
Angius
Angius2d ago
$rulesofasync
MODiX
MODiX2d ago
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:
var r = t.Result; /* ===> */ var r = await t;
t.Wait(); /* ===> */ await t;
var r = t.GetAwaiter().GetResult(); /* ===> */ var r = await t;
Task.WaitAll(t1, t2); /* ===> */ await Task.WhenAll(t1, t2);
var r = t.Result; /* ===> */ var r = await t;
t.Wait(); /* ===> */ await t;
var r = t.GetAwaiter().GetResult(); /* ===> */ var r = await t;
Task.WaitAll(t1, t2); /* ===> */ await Task.WhenAll(t1, t2);
Angius
Angius2d ago
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 awaited
WeeWeeLenin
WeeWeeLeninOP2d ago
Thank you!
Angius
Angius2d ago
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 async
WeeWeeLenin
WeeWeeLeninOP2d ago
But i must use SaveChangesAsync()?
Angius
Angius2d ago
Yes Since that actually calls the database
WeeWeeLenin
WeeWeeLeninOP2d ago
Thanks
Want results from more Discord servers?
Add your server