public RetryHandler(int maxRetries, double waitToRetryInSeconds, double maxWaitToRetryInSeconds, BackOffStrategy backOffStrategy)
        {
            MaxRetries              = maxRetries;
            WaitToRetryInSeconds    = waitToRetryInSeconds;
            MaxWaitToRetryInSeconds = maxWaitToRetryInSeconds;
            CurrentBackOffStrategy  = backOffStrategy;

            Validate();
        }
Example #2
0
        // Retry a specific codeblock wrapped in an Action delegate
        public void DoActionWithRetry(Action action, int maxRetries, int waitBetweenRetrySec, BackOffStrategy retryStrategy)
        {
            if (action == null)
            {
                throw new ArgumentNullException("No action specified");
            }

            int retryCount = 0;

            while (retryCount < maxRetries)
            {
                try
                {
                    action();
                    break;
                }
                catch (Exception ex)
                {
                    if (retryCount == maxRetries - 1)
                    {
                        DisplayError(ex);
                        throw ex;
                    }
                    else
                    {
                        //Maybe Log the number of retries
                        DisplayError(ex);

                        TimeSpan sleepTime;
                        if (retryStrategy == BackOffStrategy.Linear)
                        {
                            //Wait time is Fixed
                            sleepTime = TimeSpan.FromSeconds(waitBetweenRetrySec);
                        }
                        else
                        {
                            //Wait time increases exponentially
                            sleepTime = TimeSpan.FromSeconds(Math.Pow(waitBetweenRetrySec, retryCount));
                        }

                        Thread.Sleep(sleepTime);

                        retryCount++;
                    }
                }
            }
        }