在C#中重复一个函数,直到它不再抛出异常

psy*_*opz 8 c# exception

我有一个调用SOAP接口的类,并获取一个数据数组.但是,如果此请求超时,则会引发异常.这很好.但是,我希望我的程序再次尝试进行此调用.如果它超时,我希望继续拨打这个电话,直到它成功为止.我怎么能做到这一点?

例如:

try
{
   salesOrdersArray = MagServ.salesOrderList(sessID, filter);
}
catch
{
   ?? What Goes Here to FORCE the above line of code to rerun until it succeeds.
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 17

你只需要永远循环:

while (true)
{
    try
    {
        salesOrdersArray = MagServ.salesOrderList(sessID, filter);
        break; // Exit the loop. Could return from the method, depending
               // on what it does...
    }
    catch
    {
        // Log, I suspect...
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您几乎肯定不会真正循环.您几乎肯定会有最大的尝试次数,并且可能只捕获特定的异常.永远捕获所有异常可能是令人震惊的...想象一下,如果(非常规方法名称,顺便说一句)抛出因为你有一个bug而且是null ...你真的想永远占用100%的CPU吗?salesOrderListArgumentNullExceptionfilter


Mig*_*elo 5

您必须将 try/catch 块放置在循环构造内。如果您不希望消耗 100% 的处理器,请在 catch 块中放置 Thread.Sleep,这样每次发生异常时,它都会等待一段时间,从而释放处理器以执行其他操作。

// iterate 100 times... not forever!
for (int i = 0; i < 100; i++)
{
    try {
        // do your work here;

        break; // break the loop if everything is fine
    } catch {
        Thread.Sleep(1000);
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以指定异常类型,以便仅处理超时异常,并传递其他类型的异常。

// iterate 100 times... not forever!
for (int i = 0; i < 100; i++)
{
    try {
        // do your work here;

        break; // break the loop if everything is fine
    } catch (TimeOutException) {
        Thread.Sleep(1000);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,TimeOutException 应该替换为异常的真实名称...我不知道这是否是真实名称。

还要调整睡眠时间(以毫秒为单位)和重复次数,在我介绍的情况下,100 次 1000 毫秒的重复会产生 1 分 40 秒的最大等待时间,加上操作时间本身。