如何在catch块中实现代码?

  try
    {
       // Call a MS SQL stored procedure (MS SQL 2000)
       // Stored Procedure may deadlock
    }
    catch
    {
       // if deadlocked Call a MS SQL stored procedure (may deadlock again)
       // If deadlocked, keep trying until stored procedure executes
    }
    finally
    {

    }

最佳答案

不建议这样做,这可能会在程序中引起严重的问题。例如,如果数据库关闭了怎么办?

但是,这是循环执行的方法:

for(int attempts = 0; attempts < 5; attempts++)
// if you really want to keep going until it works, use   for(;;)
{
    try
    {
        DoWork();
        break;
    }
    catch { }
    Thread.Sleep(50); // Possibly a good idea to pause here, explanation below
}

更新:令人失望的先生在下面的评论中提到:Thread.Sleep方法将执行暂停指定的毫秒数。没有错误是完全随机的,大多数错误仅通过再试一次就能起作用仅能奏效,因为两次尝试之间的时间有所变化。暂停执行线程将为发生这种情况提供更大的机会(例如,数据库引擎有更多的启动时间)。

关于c# - 重试捕获块?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8062867/

10-10 12:32