Created
January 7, 2016 07:07
-
-
Save gekowa/984a71ff07a5e2824f2c to your computer and use it in GitHub Desktop.
Cleanest way to write a retry logic. Reference from: http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic#answer-1563234
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
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 { | |
if (retry > 0) | |
Thread.Sleep(retryInterval); | |
return action(); | |
} catch (Exception ex) { | |
exceptions.Add(ex); | |
} | |
} | |
throw new AggregateException(exceptions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment