C# 如何获取通过Polly重试策略执行的委托中的重试计数?
我正在实现Polly,以便在我的C#web应用程序中重试请求。我的示例代码包含在本文中。代码按预期工作,但传递给CreateFile()的最后一个参数(当前硬编码为0)必须是RetryAttention的值。如何在Execute操作中获取retrytry的值C# 如何获取通过Polly重试策略执行的委托中的重试计数?,c#,polly,retry-logic,C#,Polly,Retry Logic,我正在实现Polly,以便在我的C#web应用程序中重试请求。我的示例代码包含在本文中。代码按预期工作,但传递给CreateFile()的最后一个参数(当前硬编码为0)必须是RetryAttention的值。如何在Execute操作中获取retrytry的值 return Policy .Handle<HttpException>(x => x.StatusCode == (HttpStatusCode)429) .Or<StorageException&
return Policy
.Handle<HttpException>(x => x.StatusCode == (HttpStatusCode)429)
.Or<StorageException>()
.WaitAndRetry(maxRetryCount, retryAttempt => TimeSpan.FromMilliseconds(Math.Pow(retryIntervalMs, retryAttempt)))
.Execute(() => CreateFile(fileContent, containerName, fileName, connectionString, 0));
退货政策
.Handle(x=>x.StatusCode==(HttpStatusCode)429)
.或()
.WaitAndRetry(maxRetryCount,RetryAttenting=>TimeSpan.FromMillicles(Math.Pow(retryIntervalMs,RetryAttenting)))
.Execute(()=>CreateFile(fileContent,containerName,fileName,connectionString,0));
Polly不提供.Execute(…)
重载,其中重试计数是传递给的委托的输入参数之一。Execute(…)
。这是因为重试只是许多Polly策略中的一种,而.Execute(…)
重载的形式必须是所有策略类型的通用形式
对于问题中描述的用例,只需:
int count = 0;
return Policy
.Handle<HttpException>(x => x.StatusCode == (HttpStatusCode)429)
.Or<StorageException>()
.WaitAndRetry(maxRetryCount, retryAttempt => TimeSpan.FromMilliseconds(Math.Pow(retryIntervalMs, retryAttempt)))
.Execute(() => CreateFile(fileContent, containerName, fileName, connectionString, count++));
在通过策略执行的委托中,我们可以从上下文
中选择重试计数(注意处理尚未发生重试的情况):
如果您希望避免context.TryGetValue(…)
防御性代码的噪音,您也可以选择确保在开始执行之前始终初始化context[“retrycount”]
:
var myContext = new Polly.Context { {"retrycount ", 0} };
retryPolicyCapturingCountIntoContext
.Execute(
context => CreateFile(fileContent, containerName, fileName, connectionString, (int)context["retrycount"]),
myContext);
对于希望在每次重试发生时捕获重试次数的用户,例如,对于日志记录,请参阅显示如何将
retryCount
作为输入参数传递给可在策略上配置的onRetry
委托。进一步的例子
对于希望以通用方式捕获操作成功所需的总重试次数的用户(例如,作为一般执行调度基础结构代码的一部分的遥测),请参阅,它使用基于
上下文的方法。还请注意,Polly有一些。如果429响应指定等待多长时间。可以使重试策略在429响应中指定的持续时间之后完全等待重试。
retryPolicyCapturingCountIntoContext
.Execute(context =>
{
int retryCount = (context.TryGetValue("retrycount", out var retryObject) && retryObject is int count) ? count : 0;
CreateFile(fileContent, containerName, fileName, connectionString, retryCount);
}, new Context());
var myContext = new Polly.Context { {"retrycount ", 0} };
retryPolicyCapturingCountIntoContext
.Execute(
context => CreateFile(fileContent, containerName, fileName, connectionString, (int)context["retrycount"]),
myContext);