我创建了一个简单的场景来测试Polly,我可能完全错了。 如果重试,则retries变量应为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);
}
}
重试变量始终为零。那怎么办?。
答案 0 :(得分:0)
在已发布的代码中,您对Something(retries)
的呼叫不受重试策略的约束。
这是一个简单的方法调用,在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);
}
}
(为了说明必要,我对代码进行了最小的更改。)