/// <summary>
/// 重试
/// </summary>
public class RetryHandler : DelegatingHandler
{
private const int maxRetries = 3;
/// <summary>
/// 重试
/// </summary>
/// <param name="innerHandler"></param>
public RetryHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{ }
/// <summary>
/// 重试
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
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;
}
}
使用:
var client = new HttpClient(new RetryHandler(new HttpClientHandler())
本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/p/5923627.html,如需转载请自行联系原作者