【问题标题】:repeat a method or funcion 1 or more times if it throwed an exception如果抛出异常,则重复方法或函数 1 次或多次
【发布时间】:2014-12-30 03:59:39
【问题描述】:

我有这个代码 sn-p (led panel driver):

string strIP = ip1; //.Replace(',','.');
byte[] bytes = Encoding.UTF8.GetBytes(strIP);
unsafe
{
    fixed (byte* pIP = bytes)
    {
        int ddd = Huidu_InitDll(nSreenID, 2, pIP, strIP.Length + 1);
        if (ddd != 0)
        {
            MessageBox.Show("error");
            sendmail(Convert.ToString(Huidu_GetLastError()));
            return;
        }
    }
}

很多时候它会抛出错误(和电子邮件),因为我猜是高 ping。如何解决这个问题,例如尝试 3 次然后发送错误报告?

【问题讨论】:

  • 使用某种循环?问题到底出在哪里?
  • 究竟是在哪里抛出错误?
  • 问题是“ddd”变量有时为0,然后显示错误并且代码中断。我想在它中断之前再尝试两次。我应该简单地把它放在一个不同间隔的循环中还是两个 if/else 语句?

标签: c# .net function exception methods


【解决方案1】:
int retries = 3;
bool done = false;
do
{
  try { YourFunction(); done = true; }
  catch { retries--; }
while (!done && retries > 0);

if (!done)
    ShowError();

【讨论】:

    【解决方案2】:

    您可以使用基于 while 循环和计数器的简单重试机制。

    const int numTries = 3;
    int currentTry = 0;
    while (true)
    {
       if (DoTheThing())
       {
          break;
       }
       currentTry++
       if (currentTry == numTries)
       {
          //throw or report error
          break;
       }
    }
    

    【讨论】:

      【解决方案3】:

      我在一些项目中使用的这个 sn-p 代码多次尝试一个动作。它尝试一个动作指定的次数,如果发生不同类型的异常,它会立即中止。

      public static void Try(Action action, int tryCount = 3) {
          if (action == null)
              throw new ArgumentNullException("action");
          if (tryCount <= 0)
              throw new ArgumentException("tryCount");
      
      
          Exception lastException = null;
          bool lastTryFailed = true;
          int timesRemaining = tryCount;
          while (timesRemaining > 0 && lastTryFailed) {
              lastTryFailed = false;
              try {
                  action();
              } catch (Exception ex) {
                  if (ex != null && lastException != null &&
                      !(
                          ex.GetType() == lastException.GetType() ||
                          ex.GetType().IsSubclassOf(lastException.GetType()) ||
                          lastException.GetType().IsSubclassOf(ex.GetType())
                      )
                  ) {
                      throw new InvalidOperationException("Different type of exceptions occured during the multiple tried action.", ex);
                  }
      
                  // Continue
                  lastException = ex;
                  lastTryFailed = true;
              }
              timesRemaining--;
          }
          if (lastTryFailed) {
              throw new InvalidOperationException("Action failed multiple times.", lastException);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-22
        • 1970-01-01
        • 1970-01-01
        • 2018-08-27
        • 2017-05-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多