For resuming problem I used Polly
See below:
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)
{ }
// It doesn't work with Transient timeouts
////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;
////}
///
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) =>
Policy
.Handle<HttpRequestException>()
.Or<TaskCanceledException>()
.OrResult<HttpResponseMessage>(x => !x.IsSuccessStatusCode)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)))
.ExecuteAsync(() => base.SendAsync(request, cancellationToken));
}
I pass RetryHandler into HttpClient object:
this.Client = new HttpClient(new RetryHandler(new HttpClientHandler()))
{
BaseAddress = new Uri(uriText)
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…