我希望我的代码继续尝试一个方法,直到没有异常被抛出,然而,与 this question 不同的是,我希望将其编写为能够运行任何输入委托(delegate)/方法的通用方法。这是我的想法,但我不确定如何通过它传递参数或通用方法:
public void tryLoop(Delegate anyMethod, T[] arguments) {
while (true) {
// Could be replaced by timer timeout
try {
anyMethod(arguments);
break;
}
catch {
System.Threading.Thread.Sleep(2000); // wait 2 seconds
}
}
}
这可能吗?
编辑:对于它的学术,我也很想知道是否也可以返回结果。
最佳答案
如果您可以满足于使用闭包,则无需将参数全部传递给该方法(或具有多个重载)。可以使用 Func
返回结果。
public T tryLoop<T>(Func<T> anyMethod)
{
while (true)
{
try
{
return anyMethod();
}
catch
{
System.Threading.Thread.Sleep(2000); // *
}
}
return default(T);
}
void SomeMethod(int param)
{
var someLocal = "Hi";
var anotherLocal = 0;
var result = tryLoop(() =>
{
Console.WriteLine(someLocal);
return param + anotherLocal;
});
Console.Write(result);
}
老实说,我不会设置无限重试,但是 - 充其量,如果返回某些类型的 retryable
错误,例如数据库死锁或调用不稳定网络的超时服务,然后可能需要重试 3 或 4 次。诸如 DivideByZero
或 FileNotFound
之类的异常不可能通过无限期运行而消失 :-)
*** 特别是在死锁的情况下,休眠 random period建议这样做,以防万一其他线程也同时死锁在完全相同的数据上 - 您不希望在 2000 毫秒内再次发生相同的死锁 :-)。
关于c# - Try-catch until success - 通用方法或委托(delegate)的执行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23103253/