A simple but efficient retry-pattern in C#

C#AlgorithmsGenericsPatterns

Please contribute by voting. Thanks!
1

The internet isn't always super stable, and neither are all providers that you integrate with. Sometimes, you just have to try again if a request fails. I've implemented a simple retry-pattern / retry-policy in C# that mitigates this problem.

The following static generic method accepts a Func as a parameter. The Func contains the code that might have to be retried. If the Func throws a specific Exception (defined as a type parameter on the method itself) it will try again X times after Y delay between each try. The type of the return value is also defined as a type parameter.

The code looks like this:

    public static class RetryUtils
    {
        public static TRet RetryIfThrown<TException, TRet>(Func<TRet> action, int numberOfTries, int delayBetweenTries) where TException : Exception
        {
            TException lastException = null;

            for (var currentTry = 1; currentTry <= numberOfTries; currentTry++)
            {
                try
                {
                    return action();
                }
                catch (TException e)
                {
                    lastException = e;
                }
                Thread.Sleep(delayBetweenTries);
            }

            if (lastException != null) 
                throw lastException;

            throw new Exception("No exception to rethrow");
        }
    }

And this is how you can use it:

            var searchQuery = "foo";

            var data = RetryUtils.RetryIfThrown<SocketException, string>(() =>
            {
                return UnreliableService.GetData(searchQuery);

            }, 3, 250);

            Console.WriteLine("Fetched data: " + data);

If the UnreliableService throws SocketException, the RetryIfThrown method will try up to 3 times with a 250 ms delay between. All other exceptions will be thrown directly. If all goes well, the method will return the value from UnreliableService as a string.

Article created: Oct 11 at 07:36. Edited Oct 11 at 07:53.

Your comment

You need to sign up / log in to comment this article

Author

Created by Peter Wright [5] Oct 11 at 07:36

Share article

Do you know about

Cryptography?

Write an article