Cleanest way to write retry logic?

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

    Implemented LBushkin's answer in the latest fashion:

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

    and to use it:

    await Retry.Do([TaskFunction], retryInterval, retryAttempts);
    

    whereas the function [TaskFunction] can either be Task or just Task.

提交回复
热议问题