Skip to content

Instantly share code, notes, and snippets.

@MarioBinder
Last active August 15, 2017 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarioBinder/43550418b3058f774f7074818d9d0b50 to your computer and use it in GitHub Desktop.
Save MarioBinder/43550418b3058f774f7074818d9d0b50 to your computer and use it in GitHub Desktop.
wait and retry method pattern
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);
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