Occasionally I have a need to retry an operation several times before giving up. My code is like:
int retries = 3;
while(true) {
try {
DoSomething();
Building on the previous work, I thought about enhancing the retry logic in three ways:
Making it an Action
extension method
static class ActionExtensions
{
public static void InvokeAndRetryOnException (this Action action, int retries, TimeSpan retryDelay) where T : Exception
{
if (action == null)
throw new ArgumentNullException("action");
while( retries-- > 0 )
{
try
{
action( );
return;
}
catch (T)
{
Thread.Sleep( retryDelay );
}
}
action( );
}
}
The method can then be invoked like so (anonymous methods can be used as well, of course):
new Action( AMethodThatMightThrowIntermittentException )
.InvokeAndRetryOnException( 2, TimeSpan.FromSeconds( 1 ) );