一、安装包
<PackageReference Include="Polly.Core" Version="8.0.0" />
二、编写重试
ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
.AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 2,
Delay = TimeSpan.FromSeconds(3),
OnRetry = args =>
{
Console.WriteLine("OnRetry, Attempt: {0}", args.AttemptNumber);
return default;
}
})
.AddTimeout(TimeSpan.FromSeconds(100))
.Build();
pipeline.ExecuteAsync(static async cancellationToken =>
{
Console.WriteLine("重试:" + DateTime.Now);
throw new DivideByZeroException();
}, CancellationToken.None).GetAwaiter().GetResult();
三、演示