Cleanest way to write retry logic?

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

    This method allows retries on certain exception types (throws others immediately).

    public static void DoRetry(
        List retryOnExceptionTypes,
        Action actionToTry,
        int retryCount = 5,
        int msWaitBeforeEachRety = 300)
    {
        for (var i = 0; i < retryCount; ++i)
        {
            try
            {
                actionToTry();
                break;
            }
            catch (Exception ex)
            {
                // Retries exceeded
                // Throws on last iteration of loop
                if (i == retryCount - 1) throw;
    
                // Is type retryable?
                var exceptionType = ex.GetType();
                if (!retryOnExceptionTypes.Contains(exceptionType))
                {
                    throw;
                }
    
                // Wait before retry
                Thread.Sleep(msWaitBeforeEachRety);
            }
        }
    }
    public static void DoRetry(
        Type retryOnExceptionType,
        Action actionToTry,
        int retryCount = 5,
        int msWaitBeforeEachRety = 300)
            => DoRetry(new List {retryOnExceptionType}, actionToTry, retryCount, msWaitBeforeEachRety);
    

    Example usage:

    DoRetry(typeof(IOException), () => {
        using (var fs = new FileStream(requestedFilePath, FileMode.Create, FileAccess.Write))
        {
            fs.Write(entryBytes, 0, entryBytes.Length);
        }
    });
    

提交回复
热议问题