Last active
May 20, 2020 00:47
-
-
Save alastairtree/37d2cf65edee57e7a3d7 to your computer and use it in GitHub Desktop.
Retry helper
This file contains hidden or 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 RetryHelper | |
{ | |
private static ILog logger = LogManager.GetLogger(); //use a logger or trace of your choice | |
public static void RetryOnException(int times, TimeSpan delay, Action operation) | |
{ | |
var attempts = 0; | |
do | |
{ | |
try | |
{ | |
attempts++; | |
operation(); | |
break; // Sucess! Lets exit the loop! | |
} | |
catch (Exception ex) | |
{ | |
if (attempts == times) | |
throw; | |
logger.Error($"Exception caught on attempt {attempts} - will retry after delay {delay}", ex); | |
Task.Delay(delay).Wait(); | |
} | |
} while (true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment