| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 | using System;using System.Collections.Generic;using System.Threading;using Aitex.Core.RT.Event;namespace MECF.Framework.Common.Utilities{    /// <summary>    /// 在另一个线程中,指定失败次数,不断重试直到得到期望结果。    /// </summary>    public class RetryInstance    {        public static RetryInstance Instance()        {            return new RetryInstance();        }        /// <summary>        /// 执行Retry        /// </summary>        /// <param name="action">执行的方法</param>        /// <param name="secondsInterval">重试间隔(s)</param>        /// <param name="retryCount">重试次数,设置为0则无限重试</param>        /// <param name="expectedResult">期望得到的返回值</param>        /// <param name="isSuppressException">是否抑制异常</param>        /// <typeparam name="TResult">返回结果</typeparam>        /// <returns></returns>        /// <exception cref="AggregateException"></exception>        public TResult Execute<TResult>(            Func<TResult> action,            int secondsInterval,            int retryCount,            TResult expectedResult,            bool isSuppressException = true        )        {            var result = default(TResult);            var exceptions = new List<Exception>();            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;        }    }}
 |