如果抛出异常,则重复一次方法或函数1次或多次

时间:2014-11-03 13:17:35

标签: c# .net function exception methods

我有这段代码片段(led面板驱动程序):

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次然后发送错误报告?

3 个答案:

答案 0 :(得分:3)

int retries = 3;
bool done = false;
do
{
  try { YourFunction(); done = true; }
  catch { retries--; }
while (!done && retries > 0);

if (!done)
    ShowError();

答案 1 :(得分:3)

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

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);
    }
}

答案 2 :(得分:1)

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

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