· c-sharp avoid duplicate code Design patterns sample code

Generic Retry Function to Avoid Duplicate Code

Sometimes you have a method which you want to be executed again if it fails the first time.
This could lead to duplicate code, or to at least to a for loop wrapping the implementation of the method which is OK but what if you had two methods you needed this retry logic for?

You simply make a method which takes a the method you need to be executed with retry as a parameter. Like this:

private static string ExecuteWithRetry(Func<MethodResult> method, int maxRetries)
        {
            Console.WriteLine("Executing operation.");
            for (var iteration = 1; iteration <= maxRetries; iteration++)
            {
                var result = method();
                _numberOfRuns++;
                Console.WriteLine("Operation executed {0} times.", _numberOfRuns);
                if (result.Success)
                    return result.Message;

                // No luck yet - continue the loop
            }

            throw new Exception(string.Format("Method ran {0} times but did not return successful response.", RetryMax));
        }

Now how would you invoke this method?

var message = ExecuteWithRetry(MethodToRun, numberOfRetries);

That’s easy :)

If you want to see the full implementation you can get it here!

Please feel free to write a comment if you have any questions.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket