0

我创建了一个简单的场景来测试 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);
            }
        }

重试变量始终为零。又怎样 ?。

4

1 回答 1

0

在发布的代码中,您的调用Something(retries)不受重试策略的约束。这是一个简单的方法调用,称为 when retries == 0,它会立即抛出。

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

您示例中的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);
            }
        }

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

于 2018-07-24T07:47:05.373 回答