【问题标题】:c# or vb Generic function to retry code block n number of timesc# 或 vb 通用函数重试代码块 n 次
【发布时间】:2016-07-27 10:26:01
【问题描述】:

我正在尝试创建一个通用函数,我可以在其中指定要调用的方法以及在失败之前它应该尝试获取结果的次数。

类似:

//3 stands for maximum number of times GetCustomerbyId should be called if it fails on first attempt.
var result = RetryCall(GetCustomerbyId(id),3);

其次,返回类型应该根据它调用的函数自动调整。

例如,我应该能够从以下两个函数中获取结果,一个返回字符串和其他客户实体。

public static string GetCustomerFullNamebyId(int id){
    return dataContext.Customers.Where(c => c.Id.Equals(id)).SingleOrDefault().FullName;
}

public static Customer GetCustomerbyId(int id){
   return dataContext.Customers.Find(id);
}

这可能吗?

【问题讨论】:

  • 调用GetCustomerbyId(id)时失败是什么样子的?例外? null 字符串? null 对象?

标签: c# .net dynamic reflection


【解决方案1】:

您可以执行以下操作:

public T Retry<T>(Func<T> getter, int count)
{
  for (int i = 0; i < (count - 1); i++)
  {
    try
    {
      return getter();
    }
    catch (Exception e)
    {
      // Log e
    }
  }

  return getter();
}

const int retryCount = 3;

Customer customer = Retry(() => GetCustomerByID(id), retryCount);
string customerFullName = Retry(() => GetCustomerFullNamebyId(id), retryCount);

问题是在前 n 次尝试中出现异常时该怎么办?我想您可以只记录异常,但请注意调用者不会看到它。

【讨论】:

  • 感谢 vc,这就像一个魅力。正是需要的。
【解决方案2】:

您还可以执行一个循环函数并设置一个变量来查看尝试的尝试次数是否与您实际希望它执行的尝试次数匹配。

    private static void DoSomeTask(int RetryCount)
    {
        int Count = 0;
        while (Count != RetryCount)
        {
            DoCustomerLookUp(); // or whatever you want to do
            Count++;
        }
    }

【讨论】:

  • 感谢您的回答,它有效,但是将 VC 的回复标记为他首先回复的答案。
  • 也许是对这项努力的支持,但不客气:)
  • 当然,我很抱歉忘记投票了。再次感谢博士
猜你喜欢
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 2020-01-18
  • 2010-11-07
相关资源
最近更新 更多