Polly Retry with Lambda Discards

Lambda discards were introduced in C# 9. This is of great use with with Polly because there a many times that a delegate takes a series of parameters that you may not need for your purposes.

Here is an example where I only need the exception inside the onRetry. You’ll notice that in this case I also use lambda discards with the httpClientHandler.ServerCertificateCustomValidationCallback.

1
2
3
4
5
6
7
8
HttpClient httpClient = new HttpClient();
var retryPolicy = Policy.Handle<HttpRequestException>().RetryAsync(3, onRetry: (ex, _) =>
{
    Console.WriteLine($"In onRetry because {ex.InnerException.Message}");
    var httpClientHandler = new HttpClientHandler();
    httpClientHandler.ServerCertificateCustomValidationCallback = (_, _, _, _) => { return true; };
    httpClient = new HttpClient(httpClientHandler);
});

Here is another example where I am checking the status of a response to set the sleep duration of a WaitAndRetry. One line 3 I am discarding the retryCount and ctx because they are not needed inside the lambda.

 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: (_, status, _) =>
    {
        if (status.Result == Status.Unknown)
        {
            return TimeSpan.FromSeconds(1);
        }
        else
        {
            return TimeSpan.FromSeconds(2);
        }
    },
    onRetry: (status, timeSpan, retryCount, _) =>
        {
            Console.WriteLine($"Got a response of {status.Result}, retrying {retryCount}. Delaying for {timeSpan}");
        }
    );
comments powered by Disqus

Related