private static async Task Main(string[] args)
{
var timeoutPolicy = Policy
.TimeoutAsync(TimeSpan.FromSeconds(5), TimeoutStrategy.Pessimistic);
var timeoutTotalPolicy = Policy
.TimeoutAsync(TimeSpan.FromSeconds(20), TimeoutStrategy.Pessimistic);
var waitAndRetryPolicy = Policy
.Handle<Exception>()
.WaitAndRetryAsync(
2,
_ => TimeSpan.FromMilliseconds(200));
var fallbackForAnyException = Policy<string>
.Handle<Exception>()
.FallbackAsync(
_ => Task.FromResult(""),
_ => Task.CompletedTask);
var policyWrap = fallbackForAnyException
.WrapAsync(timeoutTotalPolicy)
.WrapAsync(waitAndRetryPolicy)
.WrapAsync(timeoutPolicy);
var res = await policyWrap.ExecuteAsync(async () =>
{
await Task.Delay(10);
throw new Exception("eee");
});
}
Polly 8
var pipeline = new ResiliencePipelineBuilder<bool>()
.AddFallback(new ()
{
ShouldHandle = new PredicateBuilder<bool>()
.Handle<Exception>(),
FallbackAction = static args =>
{
Console.WriteLine("Set Default Result.");
return Outcome.FromResultAsValueTask(false);
},
OnFallback = static args =>
{
if (args.Outcome.Exception != null) Console.WriteLine(args.Outcome.Exception.Message);
return default;
}
})
.AddTimeout(TimeSpan.FromSeconds(100))
.AddRetry(new ()
{
MaxRetryAttempts = 1,
Delay = TimeSpan.FromSeconds(5),
ShouldHandle = new PredicateBuilder<bool>().Handle<Exception>(),
OnRetry = static args =>
{
Console.WriteLine("OnRetry, Attempt: {0}", args.AttemptNumber);
return default;
}
})
.AddTimeout(TimeSpan.FromSeconds(3))
.Build();
var res= await pipeline.ExecuteAsync(async (ct) =>
{
await Task.Delay(TimeSpan.FromSeconds(10), ct);
return true;
});