Retry.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. namespace Aitex.Core.Utilities
  7. {
  8. /// <summary>
  9. /// 用于简化多次尝试执行动作,仅判断一次成功或者错误.类似于Trigger,但是增加了上升沿,下降沿两种逻辑
  10. /// </summary>
  11. public class Retry
  12. {
  13. /// <summary>
  14. /// 第一次触发成功
  15. /// </summary>
  16. public bool IsSucceeded { get; set; }
  17. /// <summary>
  18. /// 第一次触发失败
  19. /// </summary>
  20. public bool IsErrored { get; set; }
  21. bool _result = false;
  22. int _retryTime = -1;
  23. /// <summary>
  24. /// 当前执行结果
  25. /// </summary>
  26. public bool Result
  27. {
  28. set
  29. {
  30. if (value)
  31. {
  32. IsSucceeded = !_result;
  33. IsErrored = false;
  34. }
  35. else
  36. {
  37. IsErrored = (_result || _retryTime == -1);
  38. IsSucceeded = false;
  39. }
  40. _result = value;
  41. _retryTime = ++_retryTime % 100;
  42. }
  43. get
  44. {
  45. return _result;
  46. }
  47. }
  48. public Retry()
  49. {
  50. }
  51. public void Do(Func<bool> function, int time)
  52. {
  53. for (int i = 0; i < time; i++)
  54. {
  55. if (function())
  56. Result = true;
  57. Thread.Sleep(10);
  58. }
  59. Result = false;
  60. }
  61. }
  62. }