Cleanest way to write retry logic?

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

    For those who want to have both the option to retry on any exception or explicitly set the exception type, use this:

    public class RetryManager 
    {
        public void Do(Action action, 
                        TimeSpan interval, 
                        int retries = 3)
        {
            Try(() => {
                action();
                return null;
            }, interval, retries);
        }
    
        public T Do(Func action, 
                        TimeSpan interval, 
                        int retries = 3)
        {
            return Try(
                  action
                , interval
                , retries);
        }
    
        public T Do(Func action, 
                           TimeSpan interval, 
                           int retries = 3) where E : Exception
        {
            return Try(
                  action
                , interval
                , retries);
        }
    
        public void Do(Action action, 
                           TimeSpan interval, 
                           int retries = 3) where E : Exception
        {
            Try(() => {
                action();
                return null;
            }, interval, retries);
        }
    
        private T Try(Func action, 
                           TimeSpan interval, 
                           int retries = 3) where E : Exception
        {
            var exceptions = new List();
    
            for (int retry = 0; retry < retries; retry++)
            {
                try
                {
                    if (retry > 0)
                        Thread.Sleep(interval);
                    return action();
                }
                catch (E ex)
                {
                    exceptions.Add(ex);
                }
            }
    
            throw new AggregateException(exceptions);
        }
    }
    

提交回复
热议问题