Saturday, April 30, 2016

Retry Class C#

 


 

Using this class, taken from http://kb.zillionics.com/c-retry-pattern/ as my note

    class Retry
    {
        /// <summary>
        /// Retry calling of a method if it fails
        /// </summary>
        /// <typeparam name="T">Return data type</typeparam>
        /// <param name="method">Method</param>
        /// <param name="numRetries">Number of Retries</param>
        /// <param name="secondsToWaitBeforeRetry"></param>
        /// <returns>T</returns>
        public static T RetryMethod<T>(Func<T> method, int numRetries, int secondsToWaitBeforeRetry)
        {
            if (method == null)
                throw new ArgumentNullException("method");
            T retval = default(T);
            do
            {
                try
                {
                    retval = method();
                    return retval;
                }
                catch (Exception ex)
                {
                    //Logger.Log(ex.ToString());
                    //Logger.Log("Retrying... Count down: " + numRetries);
                    if (numRetries <= 0) throw;
                    Thread.Sleep(secondsToWaitBeforeRetry * 1000);
                }
            } while (numRetries-- > 0);
            return retval;
        }

        /// <summary>
        /// Retry calling of an Action if it fails
        /// </summary>
        /// <typeparam name="T">Return data type</typeparam>
        /// <param name="method">Method</param>
        /// <param name="numRetries">Number of Retries</param>
        /// <param name="secondsToWaitBeforeRetry"></param>
        public static void RetryAction(Action action, int numRetries, int secondsToWaitBeforeRetry)
        {
            if (action == null)
                throw new ArgumentNullException("action");
            do
            {
                try { action(); return; }
                catch (Exception ex)
                {
                    //Logger.Log(ex.ToString());
                    //Logger.Log("Retrying... Count down: " + numRetries);
                    if (numRetries <= 0) throw;
                    else Thread.Sleep(secondsToWaitBeforeRetry * 1000);
                }
            } while (numRetries-- > 0);
        }
    }
How to using it 

  string ret = Retry.RetryMethod(() => {
                                     string abac = ambildataimdb(line,  c, lines);
                                     return abac;
                                    }, 3, 5);
Or VOID


  Retry.RetryAction(() =>
                         {
                           ambildataimdb(line,  c, lines);
                                    }, 3, 5);