console.writeline中的内容不适用于Polly



目标:
显示消息"显示错误";3次尝试后。

问题:
为了实现目标,代码的哪些部分不起作用。

using Polly;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsolePollyTest2
{
class Program
{
static void Main(string[] args)
{
var maxRetryAttempts = 3;
var pauseBetweenFailures = TimeSpan.FromSeconds(2);
Policy
.Handle<HttpRequestException>()
.Or<TaskCanceledException>()
.WaitAndRetryAsync(maxRetryAttempts, i => pauseBetweenFailures)
.ExecuteAsync(PersistApplicationData2)
.ContinueWith(x =>
{
if (x.Exception != null)
{
Console.WriteLine("show error");
}
});
}

private static async Task PersistApplicationData2()
{
int ddfd = 3;
var df = ddfd / 0;
Console.WriteLine("Show data");
await Task.FromResult<object>(null);
}
}
}

谢谢!

等待你的任务首先运行,你的策略也会说,在HttpRequestExceptionTaskCanceledException的情况下,重试策略会起作用,你的方法也不例外。

如果你想测试重试策略,你可以这样做:

public static async Task Main(string[] args)
{
var maxRetryAttempts = 3;
var pauseBetweenFailures = TimeSpan.FromSeconds(2);
await Policy
.Handle<HttpRequestException>()
.Or<Exception>() //if any exception raised will try agian
.Or<TaskCanceledException>()
.WaitAndRetryAsync(maxRetryAttempts, i => pauseBetweenFailures)
.ExecuteAsync( PersistApplicationData2)
.ContinueWith(x =>
{
if (x.Exception != null)
{
Console.WriteLine("show error");
}
//success
},  scheduler: TaskScheduler.Default);
}

最新更新