Is it ok to await the same task from multiple threads – is await thread safe?

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 awaiting 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.

Leave a Comment