Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2014
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. public static class Retry
  2. {
  3. public static void Do(
  4. Type retryOnExceptionType,
  5. Action action,
  6. TimeSpan retryInterval = default(TimeSpan),
  7. int retryCount = 3)
  8. {
  9.  
  10. if (retryInterval == default(TimeSpan))
  11. retryInterval= TimeSpan.FromSeconds(1);
  12.  
  13. Do<object>(
  14. retryOnExceptionType,
  15. () =>
  16. {
  17. action();
  18. return null;
  19. },retryInterval, retryCount);
  20. }
  21.  
  22. public static T1 Do<T1,T2,T3>(
  23. Type retryOnExceptionType,
  24. Func<T2,T3,T1> action,
  25. T2 param1,
  26. T3 param2,
  27. TimeSpan retryInterval = default(TimeSpan),
  28. int retryCount = 3)
  29. {
  30. if (retryInterval == default(TimeSpan))
  31. retryInterval = TimeSpan.FromSeconds(1);
  32.  
  33. var exceptions = new List<Exception>();
  34.  
  35. for (int retry = 0; retry < retryCount; retry++)
  36. {
  37. try
  38. {
  39. return action(param1,param2);
  40. }
  41. catch (Exception ex)
  42. {
  43. if (!retryOnExceptionType.IsInstanceOfType(ex))
  44. throw;
  45.  
  46. exceptions.Add(ex);
  47. Thread.Sleep(retryInterval);
  48. }
  49. }
  50.  
  51. throw new AggregateException(exceptions);
  52. }
  53.  
  54.  
  55. public static T Do<T>(
  56. Type retryOnExceptionType,
  57. Func<T> action,
  58. TimeSpan retryInterval = default(TimeSpan),
  59. int retryCount = 3)
  60. {
  61. if (retryInterval == default(TimeSpan))
  62. retryInterval = TimeSpan.FromSeconds(1);
  63.  
  64. var exceptions = new List<Exception>();
  65.  
  66. for (int retry = 0; retry < retryCount; retry++)
  67. {
  68. try
  69. {
  70. return action();
  71. }
  72. catch (Exception ex)
  73. {
  74. if (!retryOnExceptionType.IsInstanceOfType(ex))
  75. throw;
  76.  
  77. exceptions.Add(ex);
  78. Thread.Sleep(retryInterval);
  79. }
  80. }
  81.  
  82. throw new AggregateException(exceptions);
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement