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")));
verses 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")));
Thank you for any feedback
CodePudding user response:
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://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly
