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

前端 未结 1 387
闹比i
闹比i 2020-12-03 07:07

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

相关标签:
1条回答
  • 2020-12-03 07:25

    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.

    0 讨论(0)
提交回复
热议问题