gpt4 book ai didi

c# - 波莉没有重试我的行动,我错过了什么?

转载 作者:行者123 更新时间:2023-12-04 13:23:17 27 4
gpt4 key购买 nike

public class PollyTest
{
public void RunWithPolly()
{
Console.WriteLine("RunWithPolly invoked...");
int zero = 0;
int result= 10 / zero;
}
}

在我的 Main 函数中,我创建了一个策略,如下所示:

var retryPolicy = Policy.Handle<DivideByZeroException>().Retry(3);
PollyTest pollyTest = new PollyTest();
retryPolicy.Execute(() => pollyTest.RunWithPolly());

当我执行它时,它总是在第一次运行时失败,并在 RunWithPolly 函数内部出现未处理的异常错误。

最佳答案

TL;DR 您刚刚看到 VS 调试器因异常而中断。

回复:

When I execute this, it always fails with unhandled exception error inside function "RunWithPolly" on the very first run itself

您看到的不是 Polly 或执行失败。您只是看到调试器在抛出 DivideByZeroException 时中断(在您决定是否/如何使用调试器控件继续执行之前向您展示)。

回复:

Annotating the method RunWithPolly with DebuggerStepThrough attribute resolved the problem

这并没有改变或“修复”有关执行的任何内容。它只是停止了调试器中断异常,让它看起来好像有什么不同的操作。

要向自己验证这一点,您可以声明您的 Polly 政策:

var retryPolicy = Policy
.Handle<DivideByZeroException>()
.Retry(3,
(ex, i) => { Console.Writeline($"Making retry {i} due to {ex.Message}."); }
);

然后在没有调试器的情况下运行您的示例,您将看到正在重试的所有操作。使用调试器并且不使用 [DebuggerStepThrough] 属性运行它,每次调试器中断时只需按 F5/debugger-continue,您将再次看到代码正确运行所有的重试。 [DebuggerStepThrough] 对执行没有影响,只是影响您在调试器中看到的内容。


StackOverflow q/a描述了相同的场景。

Polly wiki详细描述了发生这种情况的原因、VS 调试器对“用户未处理”异常的含义、为什么这会令人困惑,以及配置各种版本的 Visual Studio 以减少这种调试噪音的选项。

关于c# - 波莉没有重试我的行动,我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45990983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com