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

如何在Polly的WaitAndRetryAsync方法中传入重试次数参数

Hey there! Let's figure out how to pass your retrytimes value into Polly's WaitAndRetryAsync method. Looking at your current code, you're using a list of intervals to define retries, but the retrytimes array isn't actually being used—let's fix that and tie it directly to the retry count.

First, a quick note about Polly's WaitAndRetryAsync overloads: there are two common ways to specify retries:

  • Pass an IEnumerable<TimeSpan> (like your original intervals list) — the number of intervals equals the retry count.
  • Pass an explicit retry count (integer) plus a function that calculates the delay for each retry attempt.

Since you want to use retrytimes to control the retry count, here's how to adjust your code:

Step 1: Use retrytimes to define the retry count

Assuming retrytimes = [1,2,3] means you want 3 retry attempts, you can use the length of the array as your retry count. We'll also make sure the retrysecs array matches this length to avoid index errors.

Step 2: Update the WaitAndRetryAsync call

Switch to the overload that takes a retry count and a delay calculation function. This lets you explicitly pass the retry count from retrytimes and map each retry attempt to your specified delays.

Here's the revised code:

public async Task<HttpResponseMessage> RetryAPI(string request, string apiName) 
{
    var content = new HttpResponseMessage();
    var httpStatusCodesWorthRetrying = new[] {"500","502","503","504"};
    var httpStatusMessagesWorthRetrying = new[] {"InternalServerError","BadGateway","ServiceUnavailable","GatewayTimeout"};
    var retrytimes = new[] {1,2,3}; // Defines 3 retry attempts
    var retrysecs = new[] {2,4,6};  // Delays for each retry (matches retry count)

    // Validate retry count and delay count match to prevent runtime errors
    if (retrytimes.Length != retrysecs.Length)
    {
        throw new ArgumentException("Retry times count must match retry seconds count");
    }

    int retryCount = retrytimes.Length; // Extract retry count from retrytimes

    content = await Policy
        .HandleResult<HttpResponseMessage>(r => 
            httpStatusCodesWorthRetrying.Contains(((int)r.StatusCode).ToString()) 
            || httpStatusMessagesWorthRetrying.Contains(r.StatusCode.ToString()))
        .WaitAndRetryAsync(
            retryCount, 
            // retryAttempt starts at 1, so subtract 1 to index into retrysecs correctly
            retryAttempt => TimeSpan.FromSeconds(retrysecs[retryAttempt - 1])
        )
        .ExecuteAsync(async () => await ApiCall(request, apiName));

    return content;
}

Key points:

  • We use retrytimes.Length to get the exact number of retry attempts you want.
  • The retryAttempt parameter in the delay function starts at 1 (for the first retry), so we subtract 1 to match the 0-based index of retrysecs.
  • We added a validation check to ensure your retry count and delay array length match—this avoids unexpected index out-of-range errors.

If your retrytimes array is meant to hold something other than just a count (e.g., custom retry logic per attempt), you could adjust the delay function to use values from retrytimes directly, but this approach ties your retry count explicitly to the array as you requested.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 13:32:39