代替实施包裹该重试功能的
HttpClient,可以考虑构成
HttpClient与
HttpMessageHandler内部执行所述重试逻辑。例如:
public class RetryHandler : DelegatingHandler{ // Strongly consider limiting the number of retries - "retry forever" is // probably not the most user friendly way you could respond to "the // network cable got pulled out." private const int MaxRetries = 3; public RetryHandler(HttpMessageHandler innerHandler) : base(innerHandler) { } protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { HttpResponseMessage response = null; for (int i = 0; i < MaxRetries; i++) { response = await base.SendAsync(request, cancellationToken); if (response.IsSuccessStatusCode) { return response; } } return response; }}public class BusinessLogic{ public void FetchSomeThingsSynchronously() { // ... // Consider abstracting this construction to a factory or IoC container using (var client = new HttpClient(new RetryHandler(new HttpClientHandler()))) { myResult = client.PostAsync(yourUri, yourHttpContent).Result; } // ... }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)