2014-11-03 24 views
1

我有這樣的代碼片段(LED屏驅動程序):重複的方法或函數,如果1次或更多次它扔異常

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

很多時候拋出的,因爲高的錯誤(和電子郵件)我猜。如何解決例如嘗試3次然後發送錯誤報告?

+0

使用某種循環?問題究竟在哪裏? – nvoigt 2014-11-03 13:19:37

+0

它究竟在哪裏拋出錯誤? – 2014-11-03 13:22:54

+0

問題是,「ddd」變量有時爲0,然後顯示錯誤並且代碼中斷。在休息之前,我想再給它兩次嘗試。我應該簡單地把它放在一個循環中,不同的時間間隔或兩個if/else語句嗎? – tiborjan 2014-11-03 13:26:06

回答

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

if (!done) 
    ShowError(); 
1

您可以使用基於while循環和計數器的簡單重試機制。

const int numTries = 3; 
int currentTry = 0; 
while (true) 
{ 
    if (DoTheThing()) 
    { 
     break; 
    } 
    currentTry++ 
    if (currentTry == numTries) 
    { 
     //throw or report error 
     break; 
    } 
} 
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); 
    } 
} 
相關問題