Created
April 4, 2014 15:19
-
-
Save alvinashcraft/9976903 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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