Cleanest way to write retry logic?

前端 未结 29 3392
旧巷少年郎
旧巷少年郎 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:43

    You might also consider adding the exception type you want to retry for. For instance is this a timeout exception you want to retry? A database exception?

    RetryForExcpetionType(DoSomething, typeof(TimeoutException), 5, 1000);
    
    public static void RetryForExcpetionType(Action action, Type retryOnExceptionType, int numRetries, int retryTimeout)
    {
        if (action == null)
            throw new ArgumentNullException("action");
        if (retryOnExceptionType == null)
            throw new ArgumentNullException("retryOnExceptionType");
        while (true)
        {
            try
            {
                action();
                return;
            }
            catch(Exception e)
            {
                if (--numRetries <= 0 || !retryOnExceptionType.IsAssignableFrom(e.GetType()))
                    throw;
    
                if (retryTimeout > 0)
                    System.Threading.Thread.Sleep(retryTimeout);
            }
        }
    }
    

    You might also note that all of the other examples have a similar issue with testing for retries == 0 and either retry infinity or fail to raise exceptions when given a negative value. Also Sleep(-1000) will fail in the catch blocks above. Depends on how 'silly' you expect people to be but defensive programming never hurts.

提交回复
热议问题