Skip to content

Instantly share code, notes, and snippets.

@KennyBu
Created October 24, 2014 13:37
Show Gist options
  • Save KennyBu/ac56371b1666a949daf8 to your computer and use it in GitHub Desktop.
Save KennyBu/ac56371b1666a949daf8 to your computer and use it in GitHub Desktop.
C# Retry
public static class Retry
{
public static void Do(
Action action,
TimeSpan retryInterval,
int retryCount = 3)
{
Do<object>(() =>
{
action();
return null;
}, retryInterval, retryCount);
}
public static T Do<T>(
Func<T> action,
TimeSpan retryInterval,
int retryCount = 3)
{
var exceptions = new List<Exception>();
for (var retry = 0; retry <= retryCount; retry++)
{
try
{
return action();
}
catch (Exception ex)
{
exceptions.Add(ex);
Thread.Sleep(retryInterval);
}
}
throw new AggregateException(exceptions);
}
}
//Example Usage
var client = new client();
var waitTime = 2;
var numberOfRetries = 3;
var result = Retry.Do(() => client.CallWebService(parameter1, parameter2)
, TimeSpan.FromSeconds(waitTime)
, numberOfRetries);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment