簡體   English   中英

c#或vb通用函數重試代碼塊n次

[英]c# or vb Generic function to retry code block n number of times

我正在嘗試創建一個泛型函數,可以在該泛型函數中指定要調用的方法,以及在失敗之前應嘗試獲得結果的次數。

就像是:

//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);
}

這可能嗎?

您可以執行以下操作:

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次嘗試期間出現異常時該怎么辦? 我想您可以記錄該異常,但是請注意,調用者將看不到該異常。

您還可以執行循環功能並設置一個變量,以查看嘗試的次數是否與您實際希望執行的嘗試次數相匹配。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM