A simple but efficient retry-pattern in C#


Please contribute by voting. Thanks!

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++)
                    return action();
                catch (TException e)
                    lastException = e;

            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 '18. Edited Oct 11 '18.

1 Comment

Robert Bengtsson [128]  •  Sep 12 '19  •   •  Reply

Thanks! This is really nice! Can it be made to use the async-pattern as well?

Your comment

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


Created by Peter Wright [8] Oct 11 '18

Share article

Do you know about


Write an article