29 Replies
double because the method itself is async and then async again because I am using
await
No idea what "double async" means to you
The method is async because you declared it so. That's it
What if a method that is declared async calls another method that is also async? @333fred
Still not sure what double async means to you
What I just described would be it
But that doesn't mean anything to me
You declared the method async, therefore it's async
That's it, end of story
ok, thanks
What impact were you imagining that double async would have?
The outer one would be basically useless since calling a function does not need to be async-ed
But what impact do you imagine that would have?
none, really
But I guess 2 state machines would be created
Every async method gets one, and only one, state machine
It may have more states when you await, but it's still only one machine
method 2 seems better anyway since it avoids it all together
Well, Method2 isn't marked async
So it's just a normal method
yeah, but it seems to behave the same
while needing less
Exception behavior is different
Which do you favor?
Method2 will not appear in a stack trace
$itdepends
-_-
The main question is: what do you want the exception behavior to be? Do you want it to appear in a stack trace?
If so, prefer async
If you don't care, then prefer non-async
If I don't use the async method will the exception be lost or what?
Will I not be able to find the source of it?
Depends on the application type and the global sync context, but an unawaited Task could either do nothing much or crash your app
An exception from a task-returning method is (usually) observed at the await point
My plane is about to take off, so that's probably it for me responding for a while
The general rule of thumb is $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:
While you can return a
Task
from a method without it being async and without it awaiting anything, in most cases it's not a good idea if only because it disappears from the stack tracethank you, have a good flight
why does it dissapear from the stacktrace, I thought Tasks are supposed to be bascially like writing blocking code
The error is raised where the task is awaited, should that task cause an error
good little demo, helps a lot. Thank you