【问题标题】:Polly does not do the retry actionPolly 不执行重试操作
【发布时间】:2018-07-25 03:18:08
【问题描述】:

我创建了一个简单的场景来测试 Polly 我可能完全错了。 如果它重试,重试变量应该是 3。

请看看我做了什么。谢谢。

void Something(int Try)
        {
            try
            {
                if (Try <= 3)
                    throw new InvalidStudentNameException();

            }
            catch
            {

            }

        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            int retries = 0;
            try
            {
                Something(retries);
                var Result = retries;
                var response = Policy
                    .Handle<InvalidStudentNameException>()
                    .Retry(3, (exception, attempt) =>
                    {
                        retries++;
                    })
                    .Execute
                    (() => Result);

                int reachable = response;
            }
            //catch (InvalidStudentNameException SSSS)
            //{

            //}
            finally
            {
                Response.Write(retries);
            }
        }

重试变量始终为零。那怎么办?

【问题讨论】:

    标签: polly


    【解决方案1】:

    在发布的代码中,您对Something(retries) 的调用不受重试策略的约束。 这是一个简单的方法调用,在retries == 0 时调用,它直接抛出。

    对于管理对Something(...) 的调用的策略,您需要在传递给Execute(() =&gt; ) 方法的委托中执行Something(...)

    您示例中的Button1_Click(...) 方法可以修改如下:

            protected void Button1_Click(object sender, EventArgs e)
            {
                int retries = 0;
                try
                {
                    Action doSomething = () => Something(retries); // Creates an `Action` delegate which will be run by the retry policy.
                    var response = Policy
                        .Handle<InvalidStudentNameException>()
                        .Retry(3, (exception, attempt) =>
                        {
                            retries++;
                        })
                        .Execute(doSomething); // Runs the action, ie executes Something(...), within the retry policy.
    
                    int reachable = response;
                }
                //catch (InvalidStudentNameException SSSS)
                //{
    
                //}
                finally
                {
                    Response.Write(retries);
                }
            }
    

    (我对代码做了最小的改动,只是为了说明必要的情况。)

    【讨论】:

    • 谢谢。不仅您的代码有效,而且我确实遵循了另一种有效的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-14
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 2019-02-22
    相关资源
    最近更新 更多