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