In .NET 4.5, HttpClient.GetAsync()
and Async/Await cause deadlock
In .NET 4.5, when using the HttpClient
class in conjunction with the async/await
pattern, there may be an issue where the result of httpClient.GetAsync(...)
"waits" hangs indefinitely in some cases. In the provided code, this behavior was observed in the "test5" case and raises the question of whether there is a bug in the HttpClient
class or whether the API is being misused.
Cause of deadlock
Deadlocks are caused by a mismatch between the thread context and synchronization mechanism used by the async/await
pattern and the inherent thread blocking behavior of certain methods. While waiting for a Task
in the ASP.NET request context, this method will typically resume on the captured SynchronizationContext
, ensuring that the request context is preserved.
However, in the case of test5, AsyncAwait_GetSomeDataAsync
started a blocking operation, i.e. HttpClient.GetAsync
, while waiting for the result of Test5Controller.Get
. This blocks the thread that owns the request context, preventing processing of Task
in that context from completing.
Best practices for using Async/Await and HttpClient
To avoid this deadlock situation, the following best practices are recommended:
ConfigureAwait(false)
in "library" async methods whenever possible. This allows the continuation to run on a normal thread pool thread, bypassing the ASP.NET request context. Task
operations; instead, utilize the async/await
pattern throughout your code. By adhering to these practices, you can achieve both of the benefits of using async/await
: running continuations on a separate thread pool thread without the need for an ASP.NET request context, and keeping the controller itself async to prevent the request thread from blocking .
The above is the detailed content of Why Does `HttpClient.GetAsync()` Deadlock with Async/Await in .NET 4.5?. For more information, please follow other related articles on the PHP Chinese website!