Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. using System;
  2. using System.Configuration;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using log4net;
  8.  
  9. namespace Watson.Integration
  10. {
  11. public static class RetryHelper
  12. {
  13. //I am using log4net but swap in your favourite
  14. private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  15.  
  16. public static async Task RetryOnExceptionAsync(int times, TimeSpan delay, Func<Task> operation)
  17. {
  18. await RetryOnExceptionAsync<Exception>(times, delay, operation);
  19. }
  20.  
  21. public static async Task RetryOnExceptionAsync<TException>(int times, TimeSpan delay, Func<Task> operation) where TException : Exception
  22. {
  23. if (times <= 0) throw new ArgumentOutOfRangeException(nameof(times));
  24.  
  25. var attempts = 0;
  26. do
  27. {
  28. try
  29. {
  30. attempts++;
  31. await operation();
  32. break;
  33. }
  34. catch (TException ex)
  35. {
  36. if (attempts == times)
  37. throw;
  38.  
  39. await CreateDelayForException(times, attempts, delay, ex);
  40. }
  41. } while (true);
  42. }
  43.  
  44. private static Task CreateDelayForException(int times, int attempts, TimeSpan delay, Exception ex)
  45. {
  46. var delay = IncreasingDelayInSeconds(attempts);
  47. Log.Warn($"Exception on attempt {attempts} - Retying max {times} times. Sleeping for {delay}s.", ex);
  48. return Task.Delay(delay);
  49. }
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement