Created
July 20, 2019 16:28
-
-
Save FusRoDah061/9ef3f0b58f4220c9d89ef99b5aa67b4c 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
/* | |
https://stackoverflow.com/questions/1563191/cleanest-way-to-write-retry-logic/1563234?fbclid=IwAR1xkK60U07JQP8NZ0h61mWuF21AOWEfGXLrDs94PuvLI0xo7HMkdsWSQcs#1563234 | |
Usage: | |
Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1)); | |
Or | |
Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1)); | |
Or | |
int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4); | |
*/ | |
public static class Retry | |
{ | |
public static void Do( | |
Action action, | |
TimeSpan retryInterval, | |
int maxAttemptCount = 3) | |
{ | |
Do<object>(() => | |
{ | |
action(); | |
return null; | |
}, retryInterval, maxAttemptCount); | |
} | |
public static T Do<T>( | |
Func<T> action, | |
TimeSpan retryInterval, | |
int maxAttemptCount = 3) | |
{ | |
var exceptions = new List<Exception>(); | |
for (int attempted = 0; attempted < maxAttemptCount; attempted++) | |
{ | |
try | |
{ | |
if (attempted > 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