Created
February 25, 2017 22:45
-
-
Save ksysiekj/f137f7e67fa475a993685b2cd029127e 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 RetryFor<TException>(Action action, TimeSpan duration, TimeSpan delay, | |
Func<TException, bool> shouldRetry = null, Action<TException> exceptionLogger = null) | |
where TException : Exception | |
{ | |
Assert.NotNull(action, nameof(action)); | |
bool shouldRetryNotNull = shouldRetry != null; | |
double durationTotalMs = duration.TotalMilliseconds; | |
DateTime startDateTime = DateTime.Now; | |
do | |
{ | |
try | |
{ | |
action.Invoke(); | |
break; | |
} | |
catch (TException exception) | |
{ | |
if ((shouldRetryNotNull && !shouldRetry(exception)) || | |
(DateTime.Now - startDateTime).TotalMilliseconds > durationTotalMs) | |
{ | |
throw; | |
} | |
exceptionLogger?.Invoke(exception); | |
Task.Delay(delay).Wait(); | |
} | |
} while (true); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment