Esempio n. 1
0
        /// <summary>
        /// Timed Retry
        /// Calls tryFunction, if an exception is thrown it will re-attempt with a delay.
        /// Before each retry, the retryFunction is called with the retry number and exception and will throw if it returns false.
        /// </summary>
        /// <typeparam name="R"></typeparam>
        /// <param name="tryFunction"></param>
        /// <param name="retryFunction"></param>
        /// <param name="retries"></param>
        /// <param name="delay"></param>
        /// <returns></returns>
        public static R TimedRetry <R>(Func <R> tryFunction, Func <int, Exception, bool> retryFunction, RetrySettings settings)
        {
            R    result     = default(R);
            int  retryCount = 0;
            int  delay      = settings.Delay;
            bool retry      = false;

            do
            {
                try
                {
                    result = tryFunction();
                    retry  = false;
                }
                catch (Exception e)
                {
                    if (Logger.IsWarnEnabled)
                    {
                        Logger.Warn("Exception caught with retry [" + retryCount + "/" + settings.NumberRetries + "]");
                    }
                    retry = retryCount++ < settings.NumberRetries;
                    // do retry if within limit and retry function returns true
                    if (!retry || !retryFunction(retryCount, e))
                    {
                        throw;
                    }
                    if (delay > 0)
                    {
                        ThreadUtil.Await(delay);
                    }
                    // increment delay if factor supplied
                    if (settings.DelayFactor != null)
                    {
                        delay *= settings.DelayFactor.Value;
                    }
                }
            } while (retry);
            return(result);
        }
Esempio n. 2
0
 /// <summary>
 /// Timed Retry
 /// Calls tryAction, if an exception is thrown it will re-attempt with a delay.
 /// Before each retry, the retryFunction is called with the retry number and exception and will throw if it returns false.
 /// </summary>
 /// <typeparam name="R"></typeparam>
 /// <param name="tryAction"></param>
 /// <param name="retryFunction"></param>
 /// <param name="retries"></param>
 /// <param name="delay"></param>
 /// <returns></returns>
 public static void TimedRetry(Action tryAction, Func <int, Exception, bool> retryFunction, RetrySettings settings)
 {
     TimedRetry <object>(() => { tryAction(); return(null); }, retryFunction, settings);
 }