C#清洁写重试逻辑的方式? [英] C# cleanest way to write retry logic?

查看:123
本文介绍了C#清洁写重试逻辑的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候予有需要之前放弃重试操作几次。我的code是这样的:

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();
    break; // success!
  } catch {
    if(--retries == 0) throw;
    else Thread.Sleep(1000);
  }
}

我想改写这个在一般的重试功能,如:

I would like to rewrite this in a general retry function like:

TryThreeTimes(DoSomething);

是否有可能在C#中?会是什么code为 TryThreeTimes()的方法?

推荐答案

毛毯catch语句,简单地重试相同的呼叫,如果作为一般的异常处理机制可能是危险的。话虽如此,这里是一个lambda为基础的重试的包装,你可以用任何方法来使用。我选择因素重试的次数和重试超时出作为多一点灵活性参数:

Blanket catch statements that simply retry the same call can be dangerous if used as a general exception handling mechanism. Having said that, here's a lambda-based retry wrapper that you can use with any method. I chose to factor the number of retries and the retry timeout out as parameters for a bit more flexibility:

public static class Retry
{
   public static void Do(
       Action action,
       TimeSpan retryInterval,
       int retryCount = 3)
   {
       Do<object>(() => 
       {
           action();
           return null;
       }, retryInterval, retryCount);
   }

   public static T Do<T>(
       Func<T> action, 
       TimeSpan retryInterval,
       int retryCount = 3)
   {
       var exceptions = new List<Exception>();

       for (int retry = 0; retry < retryCount; retry++)
       {
          try
          { 
              if (retry > 0)
                  Thread.Sleep(retryInterval);
              return action();
          }
          catch (Exception ex)
          { 
              exceptions.Add(ex);
          }
       }

       throw new AggregateException(exceptions);
   }
}

现在您可以使用此工具方法来执行重试逻辑:

You can now use this utility method to perform retry logic:

Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));

Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));

int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);

或者,你甚至可以使一个异步过载。

这篇关于C#清洁写重试逻辑的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆