Last active
August 15, 2017 05:47
-
-
Save MarioBinder/43550418b3058f774f7074818d9d0b50 to your computer and use it in GitHub Desktop.
wait and retry method pattern
This file contains 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
WaitAndRetry.Do(MethodThatCanFail(), TimeSpan.FromSeconds(1)); | |
WaitAndRetry.Do(MethodThatCanFail(), TimeSpan.FromSeconds(1), 5); | |
AppJobResult result = WaitAndRetry.Do(() => MethodThatCanFail(), TimeSpan.FromSeconds(1)); | |
AppJobResult result = WaitAndRetry.Do(() => MethodThatCanFail(), TimeSpan.FromSeconds(1), 5); |
This file contains 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 WaitAndRetry | |
{ | |
public static void Do(Action action, TimeSpan waitInterval, int retryCount = 3) | |
{ | |
Do<object>(() => { action(); return null; }, | |
waitInterval, retryCount); | |
} | |
public static T Do<T>(Func<T> action, TimeSpan waitInterval, int retryCount = 3) | |
{ | |
var exceptions = new List<Exception>(); | |
for (int retry = 0; retry < retryCount; retry++) | |
{ | |
try | |
{ | |
if (retry > 0) | |
Thread.Sleep(waitInterval); | |
return action(); | |
} | |
catch (Exception ex) | |
{ | |
exceptions.Add(ex); | |
} | |
} | |
throw new AggregateException($"Fehler im WaitAndRetry.Do > Methode {action?.Method?.Name} konnte nach {retryCount} Versuchen nicht ausgeführt werden.", exceptions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment