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.
HttpClient.PostAsync
not being awaited below?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")));
The two code blocks you show here are effectively identical. Internally, Polly will await
the delegate anyway, and multiple await
s 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