You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Polly重试策略判断是否已耗尽所有重试次数?

Polly重试耗尽状态判断方案

针对你的需求,Polly提供了ExecuteAndCaptureAsync方法来获取执行的详细元数据,通过它可以判断是否耗尽了所有重试次数。以下是具体实现:

代码示例

// 定义最大重试次数
int maxRetries = 5;

// 构建重试策略(根据实际逻辑调整结果匹配谓词,示例为未就绪时重试)
var retryPolicy = Policy
    .Handle<PollingResult>(poll => !poll.IsReady)
    .WaitAndRetry(maxRetries, retryAttempt => RetryIntervalCalculation(retryAttempt));

// 执行并捕获重试详情
var policyResult = await retryPolicy.ExecuteAndCaptureAsync(() => SomePollingOperation());

// 判断是否耗尽所有重试且最终结果仍未满足预期
bool ranOutOfRetries = policyResult.RetryCount == maxRetries 
                       && retryPolicy.ResultPredicates.Any(pred => pred(policyResult.Result));

if (ranOutOfRetries)
{
    // 记录错误日志
    // logger.LogError("轮询操作耗尽所有重试次数仍未成功");
    throw new WeRanOutOfRetryAttemptsException("Oops!");
}

// 处理最终成功的轮询结果
var finalResult = policyResult.Result;

关键说明

  1. ExecuteAndCaptureAsync的作用:
    该方法返回PolicyResult<T>对象,包含执行过程的核心信息:

    • RetryCount:实际执行的重试次数
    • Result:最后一次轮询操作返回的结果
    • ResultPredicates:策略中定义的结果匹配规则(即Handle<PollingResult>里设置的判断条件)
  2. 重试耗尽的判断逻辑:
    当RetryCount等于预设的maxRetries,且最终返回的结果仍然符合重试触发条件时,说明所有重试已耗尽但未达到预期状态。

  3. 谓词适配:
    如果你原策略的谓词是poll => poll.IsReady(即结果就绪时触发重试),只需将判断逻辑中的谓词替换为对应规则即可,确保和策略定义的重试触发条件一致。

内容的提问来源于stack exchange,提问作者user2015635

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:50:04