0
我正在使用一组带有1或2个参数的API的外部自动化库,该参数随机抛出TargetInvocationException。第二次或第三次调用这些API通常是有效的。因此,我创建了两个辅助方法来封装多个重试逻辑将方法调用及其参数传递给不同的方法
//Original API calls
bool result1 = Foo1(true);
int result2 = Foo2(4, "abc");
//New API calls
bool result1 = SafeMethodCall(Foo1, true);
int result2 = SafeMethodCall(Foo2, 4, "abc");
//Helper Methods
public static TResult SafeMethodCall<T, TResult>(
Func<T, TResult> unSafeMethod,
T parameter)
{
int numberOfMethodInvocationAttempts = 3;
int sleepIntervalBetweenMethodInvocations = 10000;
for (int i = 0; i < numberOfMethodInvocationAttempts; i++)
{
try
{
return unSafeMethod(parameter);
}
catch (System.Reflection.TargetInvocationException ex)
{
System.Threading.Thread.Sleep(sleepIntervalBetweenMethodInvocations);
}
}
}
public static TResult SafeTargetInvocationMethodCall<T1, T2, TResult>(
Func<T1, T2, TResult> unSafeMethod,
T1 parameter1,
T2 parameter2)
{
int numberOfMethodInvocationAttempts = 3;
int sleepIntervalBetweenMethodInvocations = 10000;
for (int i = 0; i < numberOfMethodInvocationAttempts; i++)
{
try
{
return unSafeMethod(parameter1, parameter2);
}
catch (System.Reflection.TargetInvocationException ex)
{
System.Threading.Thread.Sleep(sleepIntervalBetweenMethodInvocations);
}
}
}
问题:如果你看到两个辅助方法上面有同样的身体和唯一的区别是try块内unsafeMethod通话。我怎样才能避免代码重复这里我可能必须添加接受
Func<TResult>
为另一个参数类型重载方法。
谢谢你的工作很棒! 我仍然试图围绕代表包围我的头。你能推荐任何书籍或链接,它们有更多关于lambda和代表实践的信息,而不仅仅是理论?涵盖类似于我的问题的情况? – Snak3byte 2010-07-07 20:11:42
@Anunay:恐怕不是,真的......我自己的书(深度C#)确实谈了很多关于代表的事情,但并不特别针对这种情况。 – 2010-07-07 20:35:49