Skip to content

Instantly share code, notes, and snippets.

@alvinashcraft
Created April 4, 2014 15:19
Show Gist options
  • Save alvinashcraft/9976903 to your computer and use it in GitHub Desktop.
Save alvinashcraft/9976903 to your computer and use it in GitHub Desktop.
// From StackOverflow
// Ref: http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic
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 (int retry = 0; retry < retryCount; retry++)
{
try
{
return action();
}
catch (Exception ex)
{
exceptions.Add(ex);
Thread.Sleep(retryInterval);
}
}
throw new AggregateException(exceptions);
}
}
public void TestDo()
{
Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));
Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));
int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment