/// <summary> /// 带重试的发送请求,直到判定成功或者超过次数。 /// </summary> /// <typeparam name="T">内容类型</typeparam> /// <param name="contextGenerator">创建目标HttpContext的回调</param> /// <param name="token">取消标记</param> /// <param name="maxRetryCount">最多重试次数。如果为null,则默认使用全局设置</param> /// <param name="contextChecker">判断是否正确的响应,默认为判断 IsValid 为true</param> /// <param name="retryIndicator">重试的时候将会通知</param> /// <param name="sleepTime">休息时间</param> /// <returns></returns> public Task <HttpContext <T> > SendContextWithRetryAsync <T>( [NotNull] Func <HttpContext <T> > contextGenerator, CancellationToken token, Func <HttpContext <T>, bool> contextChecker = null, Action <int, HttpContext <T> > retryIndicator = null, int?maxRetryCount = null, int?sleepTime = null ) where T : class { return(Task <HttpContext <T> > .Factory.StartNew(() => { if (contextGenerator == null) { throw new ArgumentNullException(nameof(contextGenerator)); } if (contextChecker == null) { contextChecker = _ => _.IsValid(); } HttpContext <T> context = null; maxRetryCount = maxRetryCount ?? Setting.DefaultRetryLimit; token.Register(() => { context?.Abort(); }); for (int i = 0; i < maxRetryCount.Value; i++) { context = contextGenerator(); retryIndicator?.Invoke(i, context); context.Send(); if (contextChecker(context)) { return context; } if (i < maxRetryCount.Value) { Thread.Sleep(sleepTime ?? Setting.DefaultRetrySleepTime); } } return context; })); }
/// <summary> /// 带重试的发送请求,直到判定成功或者超过次数。 /// </summary> /// <typeparam name="T">内容类型</typeparam> /// <param name="contextGenerator">创建目标HttpContext的回调</param> /// <param name="maxRetryCount">最多重试次数。如果为null,则默认使用全局设置</param> /// <param name="contextChecker">判断是否正确的响应,默认为判断 IsValid 为true</param> /// <param name="retryIndicator">重试的时候将会通知</param> /// <param name="sleepTime">两次重试之间的休息时间(毫秒)</param> /// <returns></returns> public HttpContext <T> SendContextWithRetry <T>( [NotNull] Func <HttpContext <T> > contextGenerator, Func <HttpContext <T>, bool> contextChecker = null, Action <int, HttpContext <T> > retryIndicator = null, int?maxRetryCount = null, int?sleepTime = null) where T : class { if (contextGenerator == null) { throw new ArgumentNullException(nameof(contextGenerator)); } if (contextChecker == null) { contextChecker = _ => _.IsValid(); } HttpContext <T> context = null; maxRetryCount = maxRetryCount ?? Setting.DefaultRetryLimit; for (int i = 0; i < maxRetryCount.Value; i++) { context = contextGenerator(); retryIndicator?.Invoke(i, context); context.Send(); if (contextChecker(context)) { return(context); } if (i < maxRetryCount.Value) { Thread.Sleep(sleepTime ?? Setting.DefaultRetrySleepTime); } } return(context); }