Varying the Time Between Polly Retries Based on the Result

Full source code available here.

When using the Polly Wait and Retry with a HandleResult it is possible to vary the delay between retries based on the value of the result.

The policy is below. The Result type is a Status enum. The sleepDurationProvider takes the retry count, the result, and the context as parameters. The attached zip has a console application with a fully working example.

If the Status is Unknown, the delay period is 1 second, if the Status is any other non-success status, the delay is 2 seconds.

 1ISyncPolicy<Status> waitAndRetryPolicyHandlesResult = Policy.HandleResult<Status>(s => s != Status.Success)
 2    .WaitAndRetry(5,
 3    sleepDurationProvider: (retryCount, status, ctx) =>
 4    {
 5        if (status.Result == Status.Unknown)
 6        {
 7            return TimeSpan.FromSeconds(1);
 8        }
 9        else
10        {
11            return TimeSpan.FromSeconds(2);
12        }
13    },
14    onRetry: (status, timeSpan, retryCount, ctx) =>
15        {
16            Console.WriteLine($"Got a response of {status.Result}, retrying {retryCount}. Delaying for {timeSpan}");
17        }
18    );

Here is the output.

Full source code available here.

comments powered by Disqus