console.writeline中的内容不适用于Polly [英] Content from console.writeline do not work with Polly

查看:60
本文介绍了console.writeline中的内容不适用于Polly的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Goal:
Show the message "show error" after 3 attempt.

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

Problem:
What part of the code do not work in order to achieve the goal.

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);
        }
    }
}

谢谢!

推荐答案

等待您的任务首先运行,并且在 HttpRequestException TaskCanceledException 重试策略的情况下,您的策略也会说将起作用,并且您的方法没有任何例外.

Await your task to be run first also your policy says in case of HttpRequestException or TaskCanceledException retry policy will work and your method has no any exception of those.

如果您要测试重试策略,可以执行以下操作:

If you want to test retry policy you can do some thing like this:

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);
}

这篇关于console.writeline中的内容不适用于Polly的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆