Cleanest way to write retry logic?

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

    I've implemented an async version of the accepted answer like so - and it seems to work nicely - any comments?

    
            public static async Task DoAsync(
                Action action,
                TimeSpan retryInterval,
                int maxAttemptCount = 3)
            {
                DoAsync(() =>
                {
                    action();
                    return null;
                }, retryInterval, maxAttemptCount);
            }
    
            public static async Task DoAsync(
                Func> action,
                TimeSpan retryInterval,
                int maxAttemptCount = 3)
            {
                var exceptions = new List();
    
                for (int attempted = 0; attempted < maxAttemptCount; attempted++)
                {
                    try
                    {
                        if (attempted > 0)
                        {
                            Thread.Sleep(retryInterval);
                        }
                        return await action();
                    }
                    catch (Exception ex)
                    {
                        exceptions.Add(ex);
                    }
                }
                throw new AggregateException(exceptions);
            }
    
    
    
    

    And, call it simply like this:

    var result = await Retry.DoAsync(() => MyAsyncMethod(), TimeSpan.FromSeconds(5), 4);
    

    提交回复
    热议问题