码迷,mamicode.com
首页 > Web开发 > 详细

Net中HttpClient 重试

时间:2016-09-30 15:42:59      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

/// <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())

Net中HttpClient 重试

标签:

原文地址:http://www.cnblogs.com/94cool/p/5923627.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!