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++)
catch (TException e)
lastException = e;
if (lastException != null)
throw new Exception("No exception to rethrow");
And this is how you can use it:
var searchQuery = "foo";
var data = RetryUtils.RetryIfThrown<SocketException, string>(() =>
}, 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.