Cleanest way to write retry logic?

前端 未结 29 2566
旧巷少年郎
旧巷少年郎 2020-11-22 03:01

Occasionally I have a need to retry an operation several times before giving up. My code is like:

int retries = 3;
while(true) {
  try {
    DoSomething();
         


        
29条回答
  •  长发绾君心
    2020-11-22 03:35

    Building on the previous work, I thought about enhancing the retry logic in three ways:

    1. Specifying what exception type to catch/retry. This is the primary enhacement as retrying for any exception is just plain wrong.
    2. Not nesting the last try in a try/catch, achieving slightly better performance
    3. Making it an Action extension method

      static class ActionExtensions
      {
        public static void InvokeAndRetryOnException (this Action action, int retries, TimeSpan retryDelay) where T : Exception
        {
          if (action == null)
            throw new ArgumentNullException("action");
      
          while( retries-- > 0 )
          {
            try
            {
              action( );
              return;
            }
            catch (T)
            {
              Thread.Sleep( retryDelay );
            }
          }
      
          action( );
        }
      }
      

    The method can then be invoked like so (anonymous methods can be used as well, of course):

    new Action( AMethodThatMightThrowIntermittentException )
      .InvokeAndRetryOnException( 2, TimeSpan.FromSeconds( 1 ) );
    

提交回复
热议问题