Can async deadlocks happen with HttpClient and IHttpClientFactory?

Asked 11 hours ago 21 views

0

HttpClient Gotchas

HttpClient is designed to be instantiated once and reused. Misusing it—such as creating a new instance per request or calling SendAsync synchronously via .Result—can exhaust sockets and trigger deadlocks under load.

Specific Risks

When you wrap HttpClient.SendAsync in a Task.Run and then block on it, you force the operation onto a thread-pool thread while the original context waits. If that context is a UI thread or a request thread with limited concurrency, the pool starves. IHttpClientFactory helps by managing handler lifetimes, but it does not magically fix blocking awaits.

Always await SendAsync directly. If you must call it from sync code, use SendAsync with ConfigureAwait(false) and ensure the surrounding method is also async. Never call .GetAwaiter().GetResult() inside a library meant for UI consumption.

0 Answers


Write Your Answer