Search code examples
c#asp.net-coredotnet-httpclientpolly

What Happens When HttpClient.PostAsync is Not Awaited


I'm inspecting some code that seems to throw

System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at times.

We use the library Polly for auto retries for HttpClient requests.

  • I'm starting to wonder if it has to do with the HttpClient.PostAsync not being awaited below?
  • Would that cause any connection exhaustion?

Any guidance would be appreciated.

var payload = JsonConvert.SerializeObject(data);
var response = await _pollyPolicy.ExecuteAsync(() => _httpClient.PostAsync(_endpoint, new StringContent(payload, Encoding.UTF8, "application/json")));

versus what I "think" it should be (note the async await added):

var payload = JsonConvert.SerializeObject(data);
var response = await _pollyPolicy.ExecuteAsync(async () => await _httpClient.PostAsync(_endpoint, new StringContent(payload, Encoding.UTF8, "application/json")));

Solution

  • The two code blocks you show here are effectively identical. Internally, Polly will await the delegate anyway, and multiple awaits on a Task don't have any affect.

    However, if you're only using Polly to make resilient HTTP calls with HttpClient, then I would consider using the library itself to handle that. There are examples here https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly