我正在使用带有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>
作为另一种参数类型。
答案 0 :(得分:1)
只需传入Func<TResult>
并将其称为:
bool result1 = SafeMethodCall(() => Foo1(true));
int result2 = SafeMethodCall(() => Foo2(4, "abc"));
换句话说,将参数封装在委托本身中。