简体   繁体   English

Polly 同步重试

[英]Polly synchronous Retry

I just be familiar with Polly and I'm trying to start with a simple Retry mechanism.我只是熟悉 Polly,我正在尝试从一个简单的重试机制开始。

Here's the code:这是代码:

static void Main(string[] args)
{
        Policy
            .Handle<NotImplementedException>()
            .WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(100), (exception, i, arg3) => Console.WriteLine(i))
            .Execute(() => { Console.WriteLine(Do()); });
}

private static string Do()
{
    return ++_counter < 3
        ? throw new NotImplementedException()
        : "done";
    }
}

I expected that the thrown NotImplementedException caught by Polly and retried until desired result return.我希望 Polly 捕获抛出的NotImplementedException试,直到返回所需的结果。 But at first exception raised the program stops?但起初异常引发程序停止? Where did I make a mistake?我在哪里做错了? Thanks in advance提前致谢

If I have to do same thing I can do following way.如果我必须做同样的事情,我可以按照以下方式进行。

class Program
    {
        static int _counter = 0;
        static void Main(string[] args)
        {
            Console.WriteLine(Policy
           .Handle<NotImplementedException>()
           .WaitAndRetry(3, retryAttempt => TimeSpan.FromMilliseconds(100), (exception, i, arg3) => Console.WriteLine(i))
           .Execute<string>(() => Do()));
            Console.ReadLine();
        }
        private static string Do()
        {
            Console.WriteLine(_counter);
            return ++_counter < 3
                ? throw new NotImplementedException()
                : "done";
        }
    }

Explanation:解释:

In your code you are trying to do Console.WriteLine inside Execute, it throw exception so Console.WriteLine not able to handle that things.在您的代码中,您尝试在 Execute 中执行 Console.WriteLine,它会引发异常,因此 Console.WriteLine 无法处理这些事情。 Actually you have to execute Do method and expect success result and that handle by Console.WriteLine as it will be string.实际上,您必须执行 Do 方法并期望成功结果以及 Console.WriteLine 的处理,因为它将是字符串。

Note: I still feel that your code is fine too.注意:我仍然觉得你的代码也很好。 Try to execute that from console instead of debug.尝试从控制台而不是调试执行。

Your code not working in debug mode due to following settings.由于以下设置,您的代码无法在调试模式下工作。 Uncheck this checkbox.取消选中此复选框。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM