tiborjan
tiborjan

Reputation: 31

repeat a method or funcion 1 or more times if it throwed an exception

I have this code snippet (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;
        }
    }
}

Many times it throws the error (and the email) because of the high ping I guess. How to solve that e.g. try it 3 times then send the error report?

Upvotes: 1

Views: 167

Answers (3)

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

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

if (!done)
    ShowError();

Upvotes: 3

Maarten
Maarten

Reputation: 22945

This snippet of code I used in some projects tries an action multiple times. It tries an action the specified amount of times, and if different types of exception occur it aborts immediately.

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

Upvotes: 3

Rotem
Rotem

Reputation: 21917

You can use a simple retry mechanism base on a while loop and a counter.

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

Upvotes: 1

Related Questions