[英]c# or vb Generic function to retry code block n number of times
I am trying to create a generic function to which I can specify the method to be called & number of times it should try getting result before it fails. 我正在尝试创建一个泛型函数,可以在该泛型函数中指定要调用的方法,以及在失败之前应尝试获得结果的次数。
Something like: 就像是:
//3 stands for maximum number of times GetCustomerbyId should be called if it fails on first attempt.
var result = RetryCall(GetCustomerbyId(id),3);
Secondly the return type should be adjusted automatically based on function it is calling. 其次,应根据调用的函数自动调整返回类型。
For example I should be able to get result from both of following function, one returns string & other Customer entity. 例如,我应该能够从以下两个函数中获取结果,一个返回字符串,另一个返回客户实体。
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);
}
Is this possible? 这可能吗?
You can do the following: 您可以执行以下操作:
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);
question is what to do in case of exception during the first n attempts? 问题是在前n次尝试期间出现异常时该怎么办? I guess you could just log the exception but be aware the caller won't see it. 我想您可以记录该异常,但是请注意,调用者将看不到该异常。
You could also do a loop function and set a variable to see the if the number of tries attempted match the number of tries you actually want it to do. 您还可以执行循环功能并设置一个变量,以查看尝试的次数是否与您实际希望执行的尝试次数相匹配。
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.