c#或vb通用函数重试代码块n次
我正在尝试创建一个泛型函数,我可以指定要调用的方法&它应该在失败之前尝试获取结果的次数 比如:c#或vb通用函数重试代码块n次,c#,.net,dynamic,reflection,C#,.net,Dynamic,Reflection,我正在尝试创建一个泛型函数,我可以指定要调用的方法&它应该在失败之前尝试获取结果的次数 比如: //3 stands for maximum number of times GetCustomerbyId should be called if it fails on first attempt. var result = RetryCall(GetCustomerbyId(id),3); 其次,返回类型应根据其调用的函数自动调整 例如,我应该能够从以下两个函数中得到结果,一个返回字符串,另一
//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);
public T重试(Func getter,int count)
{
对于(int i=0;i<(计数-1);i++)
{
尝试
{
返回getter();
}
捕获(例外e)
{
//日志e
}
}
返回getter();
}
常数int retryCount=3;
客户=重试(()=>GetCustomerByID(id),retryCount);
字符串customerFullName=Retry(()=>GetCustomerFullNamebyId(id),retryCount);
问题是在前n次尝试中出现异常时该怎么办?我想您可以只记录异常,但请注意调用方不会看到它。您可以执行以下操作:
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);
public T重试(Func getter,int count)
{
对于(int i=0;i<(计数-1);i++)
{
尝试
{
返回getter();
}
捕获(例外e)
{
//日志e
}
}
返回getter();
}
常数int retryCount=3;
客户=重试(()=>GetCustomerByID(id),retryCount);
字符串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++;
}
}
您还可以执行一个循环函数并设置一个变量,以查看尝试的次数是否与您实际希望它执行的次数相匹配
private static void DoSomeTask(int RetryCount)
{
int Count = 0;
while (Count != RetryCount)
{
DoCustomerLookUp(); // or whatever you want to do
Count++;
}
}
调用
GetCustomerbyId(id)
时,失败是什么样子的?例外?null
字符串?null
对象?调用GetCustomerbyId(id)
时失败是什么样子的?例外?null
字符串?一个null
对象?谢谢vc,这就像一个魔咒。这正是我们需要的。谢谢vc,这很有魅力。这正是我们需要的。谢谢你的回答。这是有效的,不过,当VC第一次回答时,他会将VC的回答标记为答案。也许是upvote的努力,但不客气:)当然,我很抱歉忘了投票。再次感谢Dr谢谢你的回答,这是有效的,但是当VC第一次回答时,他会将VC的回答标记为答案。也许是UPVOT的努力,但你不必客气:)当然,我很抱歉忘了投票。再次感谢博士