Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement re-try n times in case of exception in C#?

Tags:

c#

.net

I am developing a WPF 4.0 application in which we get the data from a remote web service. The web service exposes around 120+ methods to its clients. If a web service call from my WPF application fails, I need to retry it n times which is configurable via App.Config. How to implement this? Are there any design patterns that address this problem?

like image 657
funwithcoding Avatar asked Jan 31 '11 16:01

funwithcoding


3 Answers

I wrote this code not too long ago to do something similar to what you want. It can be modified to fit your needs. It's a generic wait method. Pass in a function and if the expected result is not returned, wait then retry and exit after X number of tries.

/// <summary>
    /// Wait for the result of func to return the expeceted result
    /// </summary>
    /// <param name="func">Function to execute each cycle</param>
    /// <param name="result">Desired result returned by func</param>
    /// <param name="waitInterval">How long to wait (ms) per cycle </param>
    /// <param name="cycles">How many times to execute func before failing</param>
    /// <returns>True if desired result was attained. False if specified time runs out before desired result is returned by func</returns>
    protected static bool WaitForEvent(Func<bool> func, bool result, int waitInterval, int cycles)
    {
        int waitCount = 0;
        while (func() != result)
        {
            if (waitCount++ < cycles)
            {
                Thread.Sleep(waitInterval);
            }
            else
            {
                return false;
            }
        }

        return true;

    }
like image 128
Dustin Davis Avatar answered Nov 18 '22 12:11

Dustin Davis


static T TryNTimes<T>(Func<T> func, int times)
{
  while (times>0)
  {
     try
     {
        return func();
     }
     catch(Exception e)
     {
       if (--times <= 0)
          throw;
     }

  }
}
like image 23
Itay Karo Avatar answered Nov 18 '22 14:11

Itay Karo


while(retries < maxTries)
   try
   {
      //retryable code here
      break;
   }
   catch(Exception ex)
   {
      if(++retries == maxTries)
         throw;
      continue;
   }

Certainly nothing fancy but it'll get the job done. The main pattern, which would be common to pretty much any implementation, is some looping construct containing and somewhat controlled by a try-catch; that can either be a recursive call or some iterative loop such as the while loop above. Make sure you exit the loop properly after a successful attempt, and keep track of retries; failure to do either will cause an infinite loop.

like image 1
KeithS Avatar answered Nov 18 '22 14:11

KeithS