Retry with the .NET Task Parallel Library (TPL)
The .NET Task Parallel Library simplifies development of and reasoning about asynchronous code. However, working with Task instances instead of blocking method results can still be difficult and un-intuitive. One example where this is true is in implementing retry logic for functions that return Task instances. Consider this helper function which retries a provided function a specified number of times:
public static Func<T> Retry(Func<T> original, int retryCount){ return () => { while (true) { try { return original(); } catch (Exception e) { if (retryCount == 0) { throw; } retryCount--; } } };}This was a response to this Stackoverflow.com question and works as expected for blocking methods.
However, suppose you have a function which returns a Task
/// <summary> /// Utility methods for <see cref="System.Threading.Tasks.Task"/>. /// </summary> public static class TaskHelper { /// <summary> /// Returns a task which retries the task returned by the specified task provider. /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="taskProvider">The task returning function.</param> /// <param name="maxAttemps">The maximum number of retries.</param> /// <param name="shouldRetry">A predicate function which determines whether an exception should cause a retry. The default returns true for all exceptions.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.ArgumentOutOfRangeException"></exception> public static Task<TResult> Retry<TResult>(Func<Task<TResult>> taskProvider, int maxAttemps, Func<Exception, bool> shouldRetry = null) { Require.NotNull(taskProvider); Require.Positive(maxAttemps, "maxAttemps"); if (shouldRetry == null) shouldRetry = ex => true; return taskProvider() .ContinueWith(task => RetryContinuation(task, taskProvider, maxAttemps, shouldRetry)); }
/// <summary> /// A task continuation which attempts a retry if a task is faulted. /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="task"></param> /// <param name="taskProvider"></param> /// <param name="attemptsRemaining"></param> /// <param name="shouldRetry"></param> /// <returns></returns> static TResult RetryContinuation<TResult>(Task<TResult> task, Func<Task<TResult>> taskProvider, int attemptsRemaining, Func<Exception, bool> shouldRetry) { if (task.IsFaulted) { if (attemptsRemaining > 0 && shouldRetry(task.Exception.InnerException)) { return taskProvider() .ContinueWith(retryTask => RetryContinuation(retryTask, taskProvider, --attemptsRemaining, shouldRetry)) .Result; } else { // will throw AggregateException return task.Result; } } else { return task.Result; } } }The core functionality is in the RetryContinuation method. It takes a task instance, the original task returning function, a number of remaining attempts and a predicate function which determines whether a given exception should result in a retry. This function calls itself recursively until the task is either successful or the maximum number of attempts have been reached.