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.

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

Here is the output.

Full source code available here.

comments powered by Disqus

Related