Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Configuration;
- using System.Linq;
- using System.Reflection;
- using System.Threading;
- using System.Threading.Tasks;
- using log4net;
- namespace Watson.Integration
- {
- public static class RetryHelper
- {
- //I am using log4net but swap in your favourite
- private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- public static async Task RetryOnExceptionAsync(int times, TimeSpan delay, Func<Task> operation)
- {
- await RetryOnExceptionAsync<Exception>(times, delay, operation);
- }
- public static async Task RetryOnExceptionAsync<TException>(int times, TimeSpan delay, Func<Task> operation) where TException : Exception
- {
- if (times <= 0) throw new ArgumentOutOfRangeException(nameof(times));
- var attempts = 0;
- do
- {
- try
- {
- attempts++;
- await operation();
- break;
- }
- catch (TException ex)
- {
- if (attempts == times)
- throw;
- await CreateDelayForException(times, attempts, delay, ex);
- }
- } while (true);
- }
- private static Task CreateDelayForException(int times, int attempts, TimeSpan delay, Exception ex)
- {
- var delay = IncreasingDelayInSeconds(attempts);
- Log.Warn($"Exception on attempt {attempts} - Retying max {times} times. Sleeping for {delay}s.", ex);
- return Task.Delay(delay);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement