using System;
using System.Collections.Generic;
using System.Threading;
using Aitex.Core.RT.Event;
namespace MECF.Framework.Common.Utilities
{
///
/// 在另一个线程中,指定失败次数,不断重试直到得到期望结果.
///
public class RetryInstance
{
public static RetryInstance Instance()
{
return new RetryInstance();
}
///
/// 执行Retry
///
/// 执行的方法
/// 重试间隔(s)
/// 重试次数,设置为0则无限重试
/// 期望得到的返回值
/// 是否抑制异常
/// 返回结果
///
///
public TResult Execute(
Func action,
int secondsInterval,
int retryCount,
TResult expectedResult,
bool isSuppressException = true
)
{
var result = default(TResult);
var exceptions = new List();
if (retryCount == 0)
{
retryCount = Int32.MaxValue;
}
for (var retry = 0; retry < retryCount; retry++)
{
try
{
if (retry > 0) Thread.Sleep(secondsInterval * 1000);
EV.PostInfoLog(action.ToString(),$"Retry Instance executing {retry+1} times, result : {result}");
result = action();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
if (result.Equals(expectedResult)) return result;
}
if (!isSuppressException)
throw new AggregateException(exceptions);
else
return result;
}
}
}