MethodInfo Invoke方法的异常Handeling

时间:2017-04-12 14:32:04

标签: c# exception-handling

我对异常处理程序进行了一般性的重试,我希望它能在一定时间内重复一个函数,这里有代码

public static void Retry(this MethodInfo methodInfo, object[] parametrsList, short after = 0, short? retry = 1)
{
    if (retry < 0)
        return;
    try
    {
        short waitingPeriodMs = after*1000;
        Thread.Sleep(waitingPeriodMs);
        Type classObjType = methodInfo.ReflectedType;
        object classObj = Activator.CreateInstance(classObjType);
        methodInfo.Invoke(classObj, parametrsList);
    }
    catch (TargetInvocationException ex)
    {
        Debug.WriteLine("Exception Caught");
        methodInfo.Retry(parametrsList, after, --retry);
    }
    catch (Exception ex)
    {
        Debug.WriteLine("Exception Caught");
        methodInfo.Retry(parametrsList, after, --retry);
    }
}

问题是每当我在方法中抛出未处理的异常时我都不会调用两个catch语句捕获它 我确保未选中仅使用我的代码复选框

我已经使用了这两个Debug.Writeline语句来确保它不是与调试器相关的问题,并检查了Output窗口并确保这两个语句没有被执行

P.S。我知道在异常代码上使用一般性重试是有风险的,并且由于项目相关的原因,可能导致我使用它进行无限次的重试

更新 重现问题的单元测试示例

[TestClass]
public class ExceptionTest
{
    [TestMethod]
    public void TestExceptionRetry()
    {
        Action act = () => { throw new Exception(); };
        act.Method.Retry(new object[0]);
    }
}

0 个答案:

没有答案