Cleanest way to write retry logic?

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

    Allowing for functions and retry messages

    public static T RetryMethod(Func method, int numRetries, int retryTimeout, Action onFailureAction)
    {
     Guard.IsNotNull(method, "method");            
     T retval = default(T);
     do
     {
       try
       {
         retval = method();
         return retval;
       }
       catch
       {
         onFailureAction();
          if (numRetries <= 0) throw; // improved to avoid silent failure
          Thread.Sleep(retryTimeout);
       }
    } while (numRetries-- > 0);
      return retval;
    }
    

提交回复
热议问题