bhaelochon
9/21/2015 - 9:49 AM

Retry helper

Retry helper

public static class RetryHelper
{
    private static ILog logger = LogManager.GetLogger(); //use a logger or trace of your choice
    
    public static void RetryOnException(int times, TimeSpan delay,  Action operation)
    {
        var attempts = 0;
        do
        {
            try
            {
                attempts++;
                operation();
                break; // Sucess! Lets exit the loop!
            }
            catch (Exception ex)
            {               
                if (attempts == times)
                    throw;
                
                logger.Error($"Exception caught on attempt {attempts} - will retry after delay {delay}", ex);   
                             
                Task.Delay(delay).Wait();
            }
        } while (true);
    }
}