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.

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

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.

 1ISyncPolicy<Status> waitAndRetryPolicyHandlesResult = Policy.HandleResult<Status>(s => s != Status.Success)
 2    .WaitAndRetry(5,
 3    sleepDurationProvider: (_, status, _) =>
 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, _) =>
15        {
16            Console.WriteLine($"Got a response of {status.Result}, retrying {retryCount}. Delaying for {timeSpan}");
17        }
18    );
comments powered by Disqus

Related