Skip to content

Instantly share code, notes, and snippets.

@johnnyhalife
Created June 23, 2010 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnnyhalife/449695 to your computer and use it in GitHub Desktop.
Save johnnyhalife/449695 to your computer and use it in GitHub Desktop.
/// Runs the given delegate up to N times before throwing an exception,
/// if the thrown exception matches a given criteria (retryCondition).
/// </summary>
/// <typeparam name="T">The return type of the delegate.</typeparam>
/// <param name="numberOfRetries">The number of retries.</param>
/// <param name="operation">The delegate to be executed.</param>
/// <param name="retryCondition">A predicate that when evaluated indicates whether the action should be retried.</param>
/// <param name="onRetryAction">An action to be executed before executing the retry.</param>
/// <param name="onErrorAction">An action to be executed before the last chance of the exception is thrown.</param>
/// <returns>The result of the operation.</returns>
public T Run<T>(int numberOfRetries, Func<TableStore, T> operation, Predicate<Exception> retryCondition, Action<Exception> onRetryAction, Action<Exception> onErrorAction)
{
int counter = 0;
if (retryCondition == null)
throw new InvalidOperationException("You cannot run without a Retry Condition Predicate");
if (operation == null)
throw new InvalidOperationException("Operation delegate cannot be null");
var result = default(T);
while (counter < numberOfRetries)
{
try
{
result = operation.Invoke(this.store);
break;
}
catch (Exception e)
{
counter++;
if (!retryCondition.Invoke(e) || counter == numberOfRetries)
{
if (onErrorAction != null)
onErrorAction.Invoke(e);
throw;
}
if (onRetryAction != null)
onRetryAction.Invoke(e);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment