场景:
在另一个线程中,指定失败次数,不断重试直到得到期望结果。
工具类:
public class Retry
{
public static Retry Instance(){
return new Retry();
}
public TResult Execute<TResult>(
Func<TResult> action,
int secondsInterval,
int retryCount,
TResult expectedResult,
bool isSuppressException = true
)
{
TResult result = default(TResult);
var exceptions = new List<Exception>();
for (var retry = 0; retry < retryCount; retry++)
{
try
{
if (retry > 0){
Thread.Sleep(secondsInterval * 1000);
}
result = action();
Console.WriteLine(string.Format("executing {0} times, result : {1}",retry+1,result));
}
catch (Exception ex)
{
exceptions.Add(ex);
}
if (result.Equals(expectedResult)){
return result;
}
}
if (!isSuppressException){
throw new AggregateException(exceptions);
}
else{
return result;
}
}
}
使用示例:
void Main()
{
try{
var expected = 5;
var retryCount = 10;
var ret = Retry.Instance().Execute<int>(()=>{var r = new Random(); return r.Next(10);},1,retryCount,expected);
if(expected == ret)
Console.WriteLine("done. got result : " + ret);
else
Console.WriteLine("tried {0} times , failed to get expected result : {1}",retryCount,expected);
}
catch (Exception ex){
Console.WriteLine(ex.Message);
}
}