Why does Task.WaitAll() not block or cause a deadlock here?

前端 未结 3 1817
野的像风
野的像风 2020-12-09 05:41

In the example below two await calls are used. To gain performance, the sample gets converted Task.WaitAll() instead (not really any faster, but th

3条回答
  •  一生所求
    2020-12-09 05:59

    When you're blocking the UI thread (and the current synchronization context) it will only cause a deadlock if one of the tasks that you're waiting on marshals a delegate to the current context and then waits on it (synchronously or asynchronously). Synchronously blocking on any async method isn't an instant deadlock in every single case.

    Because async methods will, by default, marshal the remainder of the method to the current synchronization context and after every single await, and because the task will never finish until that happens, it means that synchronously waiting on methods that use async/await will often deadlock; at least unless the described behavior is explicitly overridden (through, say ConfigureAwait(false)).

    Using WhenAll means that you're not blocking the current synchronization context. Instead of blocking the thread you're just scheduling another continuation to be run when all of the other tasks finish, leaving the context free to handle any other requests that are ready right now (like, say, the continuation from the underlying async method that WhenAll is waiting on).

提交回复
热议问题