未等待 HttpClient.PostAsync 时会发生什么

What Happens When HttpClient.PostAsync is Not Awaited

我正在检查一些似乎抛出错误的代码

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

我们使用库 Polly 自动重试 HttpClient 请求。

如有任何指导,我们将不胜感激。

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

与我“认为”应该是什么(注意添加的 async await):

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

您在此处显示的两个代码块实际上是相同的。 Internally,Polly 无论如何都会 await 代表,Task 上的多个 await 没有任何影响。

但是,如果您仅使用 Polly 通过 HttpClient 进行弹性 HTTP 调用,那么我会考虑使用库本身来处理它。这里有例子https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly