Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try, Catch Problem

I've noticed this problem happening a lot in most things I do, so I'm thinking there must be a design pattern for this.

Basically if an exception is thrown, attempt to solve the problem and retry. If I place it in the try, all it will do is catch the exception, but I want to retry whatever it was doing and if it fails again, retry again a certain number of times.

Is there a common pattern for this sort of stuff?

like image 454
James Jeffery Avatar asked Feb 09 '10 17:02

James Jeffery


2 Answers

check this SO answer.. hope that helps u

Cleanest way to write retry logic?

public static class RetryUtility
{
   public static void RetryAction(Action action, int numRetries, int retryTimeout)
   {
       if(action == null)
           throw new ArgumenNullException("action"); 

       do
       {
          try 
          {  
              action(); 
              return;  
          }
          catch
          { 
              if(numRetries <= 0) 
                  throw;  // Avoid silent failure
              else
              {
                  Thread.Sleep(retryTimeout);
                  numRetries--;
              }
          }
       } 
       while(numRetries > 0);
   }
}

Call

RetryUtility.RetryAction( () => SomeFunctionThatCanFail(), 3, 1000 );

Credit goes to LBushkin

like image 127
Jeeva Subburaj Avatar answered Oct 20 '22 01:10

Jeeva Subburaj


This runs indefinately but it would be easy to add a loop counter to the while clause

    var solved = false;
    var tries = 0;

    while (!solved)
    {
         try
         {
            //Do Something
            solved = true;
         }
         catch
         {
             //Fix error
         } 
         finally
         {
              if(solved || IsRediculous(tries))
                 break;

              tries++;
         }
    }
like image 30
James Barrass Avatar answered Oct 20 '22 01:10

James Barrass