Skip to content

Instantly share code, notes, and snippets.

@ksysiekj
Created February 25, 2017 22:09
Show Gist options
  • Save ksysiekj/d63e1f563ddcb85cddf4b6c28e21da8c to your computer and use it in GitHub Desktop.
Save ksysiekj/d63e1f563ddcb85cddf4b6c28e21da8c to your computer and use it in GitHub Desktop.
public static void Retry<TException>(Action action, int maxAttempts, TimeSpan delay,
Func<TException, bool> shouldRetry = null, Action<TException> exceptionLogger = null)
where TException : Exception
{
Assert.Positive(maxAttempts, nameof(maxAttempts));
Assert.NotNull(action, nameof(action));
bool shouldRetryNotNull = shouldRetry != null;
for (;;) // while (true)
{
try
{
action.Invoke();
break;
}
catch (TException exception)
{
if ((shouldRetryNotNull && !shouldRetry(exception)) || ZERO == (--maxAttempts))
{
throw;
}
exceptionLogger?.Invoke(exception);
Task.Delay(delay).Wait();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment