/// <summary>
/// 错误重试处理
/// </summary>
public static class RetryHandle
{
/// <summary>
/// 重试
/// </summary>
/// <param name="count">重试次数</param>
/// <param name="actionFunc">执行方法</param>
public static T Retry<T>(int count, Func<int,RetryMessage<T>> actionFunc = null)
{
if (actionFunc == null) return default(T);
var times = 1;
RetryMessage<T> ret;
do
{
ret = actionFunc(
times
);
if (ret.Success) break;
times++;
} while (times <= count);
return ret.Data;
}
/// <summary>
/// 隔一段时间重试调用一次
/// </summary>
/// <param name="sleepDurations"></param>
/// <param name="action"></param>
public static void WaitAndRetry(IEnumerable<TimeSpan> sleepDurations, Action<TimeSpan, int> action)
{
var intento = 1;
sleepDurations.Each(timeSpan =>
{
System.Threading.Thread.Sleep(timeSpan.Seconds * 1000);
action(timeSpan, intento);
intento++;
});
}
}
/// <summary>
///
/// </summary>
public class RetryMessage<T>
{
/// <summary>
///
/// </summary>
public bool Success { set; get; }
/// <summary>
///
/// </summary>
public T Data { set; get; }
}
//调用示例
var ret = RetryHandle.Retry(3, () =>
{
var list = GetList();
return new RetryMessage<List<HO_PESbkv>>
{
Success = list != null && list.Any(),
Data = list
};
});