RetryInstance.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using Aitex.Core.RT.Event;
  5. namespace MECF.Framework.Common.Utilities
  6. {
  7. /// <summary>
  8. /// 在另一个线程中,指定失败次数,不断重试直到得到期望结果.
  9. /// </summary>
  10. public class RetryInstance
  11. {
  12. public static RetryInstance Instance()
  13. {
  14. return new RetryInstance();
  15. }
  16. /// <summary>
  17. /// 执行Retry
  18. /// </summary>
  19. /// <param name="action">执行的方法</param>
  20. /// <param name="secondsInterval">重试间隔(s)</param>
  21. /// <param name="retryCount">重试次数,设置为0则无限重试</param>
  22. /// <param name="expectedResult">期望得到的返回值</param>
  23. /// <param name="isSuppressException">是否抑制异常</param>
  24. /// <typeparam name="TResult">返回结果</typeparam>
  25. /// <returns></returns>
  26. /// <exception cref="AggregateException"></exception>
  27. public TResult Execute<TResult>(
  28. Func<TResult> action,
  29. int secondsInterval,
  30. int retryCount,
  31. TResult expectedResult,
  32. bool isSuppressException = true
  33. )
  34. {
  35. var result = default(TResult);
  36. var exceptions = new List<Exception>();
  37. if (retryCount == 0)
  38. {
  39. retryCount = Int32.MaxValue;
  40. }
  41. for (var retry = 0; retry < retryCount; retry++)
  42. {
  43. try
  44. {
  45. if (retry > 0) Thread.Sleep(secondsInterval * 1000);
  46. EV.PostInfoLog(action.ToString(),$"Retry Instance executing {retry+1} times, result : {result}");
  47. result = action();
  48. }
  49. catch (Exception ex)
  50. {
  51. exceptions.Add(ex);
  52. }
  53. if (result.Equals(expectedResult)) return result;
  54. }
  55. if (!isSuppressException)
  56. throw new AggregateException(exceptions);
  57. else
  58. return result;
  59. }
  60. }
  61. }