Task.WaitAll hanging with multiple awaitable tasks in ASP.NET Task.WaitAll hanging with multiple awaitable tasks in ASP.NET asp.net asp.net

Task.WaitAll hanging with multiple awaitable tasks in ASP.NET


Rather than Task.WaitAll you need to use await Task.WhenAll.

In ASP.NET you have an actual synchronization context. This means that after all await calls you will be marshaled back to that context to execute the continuation (effectively serializing these continuations). In a console app there is no synchronization context, so all of the continuations are just sent to the thread pool. By using Task.WaitAll in the request's context you're blocking it, which is preventing it from being used to handle the continuations from all of the other tasks.

Also note that one of the primary benefits of async/await in an ASP app is to not block the thread pool thread that you're using to handle the request. If you use a Task.WaitAll you're defeating that purpose.

A side effect of making this change is that by moving from a blocking operation to an await operation exceptions will be propagated differently. Rather than throwing AggregateException it will throw one of the underlying exceptions.