Is await thread safe? It seems the Task class is thread safe so I guess awaiting it is also thread safe but I haven\'t found a confirmation anywhere. Also is thread safety a
As you alluded to, await
is thin enough that it doesn't see threads in the first place.
The code associated with await
(the compiler-generated code within the state machine, and the support classes in the BCL) will only ever run on one thread at a time. (it can switch to a different thread when coming back from the awaitable, but the previous run will have already finished)
The actual thread-safety depends on the object you're awaiting.
It must have a thread-safe way to add callbacks (or await
ing it twice at once may break).
In addition, it must call the callback exactly once, or it may break the state machine. (in particular, if it runs its callback on two threads at the same time, things will go horribly wrong)
Task
is thread-safe.