Created
February 25, 2017 22:09
-
-
Save ksysiekj/d63e1f563ddcb85cddf4b6c28e21da8c to your computer and use it in GitHub Desktop.
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 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