来自 console.writeline 的内容不适用于 Polly

Content from console.writeline do not work with 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);
}