2016-04-06 24 views
0

我想创建一个通用函数,我可以指定要调用的方法&它应该尝试在失败之前获取结果的次数。c#或vb通用函数重试代码块n次数

喜欢的东西:

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

其次,返回类型应该会自动根据功能被调用调整。

例如我应该可以从以下两个函数中得到结果,一个返回字符串&其他Customer实体。

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

这可能吗?

+0

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

回答

2

你可以做到以下几点:

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尝试过程中的异常情况下怎么办?我想你可以只记录异常但知道调用者不会看到它。

+0

感谢vc,这就像一个魅力。确切需要什么。 – Robin

2

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

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

感谢您的回答,但是将VC的回复作为回答,正如他先回答的那样。 – Robin

+0

也许upvote的努力,但不客气:) –

+0

当然,我的道歉忘了投票。谢谢博士 – Robin