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

Polly v8.3:无返回值方法重试耗尽后执行终态代码的正确方式

Polly v8.3 非泛型重试耗尽后执行收尾逻辑的方案

针对你使用非泛型ResiliencePipeline实现重试,需要在最后一次重试失败后执行指定逻辑的需求,以下是两种Polly标准解决方案,无需修改原有void方法的返回值:

方案一:利用重试策略的OnRetryCompleted回调

在配置RetryStrategyOptions时,通过OnRetryCompleted回调监听所有重试完成后的状态,判断是否是重试耗尽后的最终失败,再执行收尾逻辑:

var retryOptions = new RetryStrategyOptions
{
    MaxRetryAttempts = 5,
    // 每次失败记录日志的逻辑
    OnRetry = args =>
    {
        Console.WriteLine($"重试第 {args.AttemptNumber} 次,失败原因:{args.Exception.Message}");
        return ValueTask.CompletedTask;
    },
    // 重试完成后的收尾逻辑触发点
    OnRetryCompleted = args =>
    {
        // 判断是否是重试耗尽后最终失败
        if (args.Outcome.Exception != null && args.AttemptNumber == args.RetryOptions.MaxRetryAttempts)
        {
            // 执行发送邮件等自定义逻辑
            SendFailureNotificationEmail();
        }
        return ValueTask.CompletedTask;
    }
};

ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
    .AddRetry(retryOptions)
    .Build();

pipeline.Execute(() => SomeVoidMethodThatMayFail());

说明

  • OnRetryCompleted会在所有重试尝试(包括最后一次失败)完成后触发
  • 通过args.Outcome.Exception判断最终执行是否失败,结合args.AttemptNumber与MaxRetryAttempts的对比,确认是重试耗尽后的失败场景

方案二:使用ExecuteAndCapture捕获执行结果

通过ExecuteAndCapture方法替代Execute,它会捕获执行的最终状态,无需处理异常,直接根据结果判断是否需要执行收尾逻辑:

ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 5,
        OnRetry = args =>
        {
            Console.WriteLine($"重试第 {args.AttemptNumber} 次,失败原因:{args.Exception.Message}");
            return ValueTask.CompletedTask;
        }
    })
    .Build();

// 捕获执行的最终结果,不会抛出异常
var outcome = pipeline.ExecuteAndCapture(() => SomeVoidMethodThatMayFail());

// 如果最终执行失败(即重试耗尽后仍未成功)
if (outcome.Status == OutcomeStatus.Failure)
{
    SendFailureNotificationEmail();
}

说明

  • ExecuteAndCapture会包装执行过程,无论是否抛出异常都返回ResilienceOutcome对象
  • 当outcome.Status为OutcomeStatus.Failure时,说明重试策略已耗尽所有重试次数且最终执行失败,此时可直接触发收尾逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:31:08