Retry policies in C#
Transient failure, meet declarative persistence.
using Polly;
using Polly.Retry;
var pipeline = new ResiliencePipelineBuilder()
.AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 3,
Delay = TimeSpan.FromMilliseconds(50),
BackoffType = DelayBackoffType.Exponential,
})
.Build();
var attempts = 0;
pipeline.Execute(() =>
{
attempts++;
if (attempts < 3) throw new TimeoutException("flaky");
});
Console.WriteLine($"succeeded on attempt {attempts}");
How it works
- A
ResiliencePipelineis built once and reused. MaxRetryAttempts,Delayand exponential backoff are options.- The flaky callback succeeds on attempt three, inside the budget.
Keywords and builtins used here
ifnewthrowusingvar
The run, in numbers
- Lines
- 19
- Characters to type
- 404
- Tokens
- 84
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 59 seconds.
Step 1 of 2 in Resilience with Polly, step 8 of 16 in The open ecosystem.