Home > Enterprise >  What is the most efficient way to write this retry logic for a try-catch? C#
What is the most efficient way to write this retry logic for a try-catch? C#

Time:10-07

I have a C# task that I'd like to re run if a certain exception type is thrown.

This is what I have currently:

bool retry = true;
int numOfRetries = 3;
int tries;

while (retry = true && tries <= numOfRetries)
{
    try
    {
         //Task
         retry = false;
    }
    catch (Exception e)
    {
        if (e.Message.Contains("Unique exception Id like to retry on")
        {
        tries  ;
        }
        else
        {
        retry = false; 
        log(e);
        }
    }
}



CodePudding user response:

I suggest using for not while:

for (int retry = 1; retry <= numOfRetries;   retry) {
  try {
    DoSomething();

    break; // stop looping on success
  }
  catch (Exception e) {
    //TODO: put here condition on e where you should retry
    if (!condition) { // <- no retry
      log(e);
      // you may want to rethrow the exception: throw;

      break; // no more retries on unwanted exception
    }  
  }
}

If you want to catch certain exception types:

for (int retry = 1; retry <= numOfRetries;   retry) {
  try {
    DoSomething();

    break; // stop looping on success
  }
  catch MyException1:
  catch MyException2:
  catch MyExceptionN:
    ; // catch and do nothing but retry
  catch (Exception e) {
    // no retry
    log(e);
    // you may want to rethrow the exception: throw;

    break; // no more retries on unwanted exception
  }
}

CodePudding user response:

Take a look at the Polly library: https://github.com/App-vNext/Polly It has a good retry policy and it's easy to implement.

  • Related