【问题标题】:C# retry logic While loop [duplicate]C#重试逻辑While循环[重复]
【发布时间】:2019-10-17 21:48:18
【问题描述】:

我在完成我的重试逻辑代码时遇到了一点麻烦。但是,我无法弄清楚缺少的部分。如何在失败时捕获和记录并使用计时器重试。

这是我的代码。

while (true)
{
    var res = await this.httpClientWrapper.......

    if (res.IsSuccessStatusCode)
    {
        var result = await res.Content.......
        this.logger.Info($".......
    }

    if (result.status == "Succesed")
    {
        return true;
    }
    else
    {
        var resContent = await.......
        this.logger.Info($.......
        await Task.Delay(2000).ConfigureAwait(false);
        throw new Exception(resContent);
    }                    
}

【问题讨论】:

  • 您的result 变量在if 块的范围内声明,因此您无法在下一个if 行中访问它。
  • @RufusL 我认为第二个 res 也可能是 await this.httpClientWrapper....... 其实...我不知道...
  • 您不能在抛出异常的同时仍然循环。您必须在循环内处理异常。用try...catch 包围循环内的代码,并在catch 中处理异常(日志等)。

标签: c# asp.net


【解决方案1】:

我建议您不要尝试重新发明轮子,而只是重复使用 Polly 框架:

var maxRetryAttempts = 3;

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(maxRetryAttempts, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2,retryAttempt)));

try {
  await retryPolicy.ExecuteAsync(async () =>
  {
    var response = await this.httpClientWrapper.......
    response.EnsureSuccessStatusCode();
  });
}
catch(HttpRequestException ex)
{
  // You've already retried 3 times and failed, do something else here
}
catch(Execption ex)
{
  // You've got a non-HttpRequestException, so we didn't retry.
}

这将重试 3 次,然后,您将获得 HttpException,您可以捕获并执行您想要的任何操作。我已经为您实现了指数退避,但如果您愿意,可以将其更改为每两秒一次。

【讨论】:

    【解决方案2】:
    while(!DoThings()) {
       await Task.Delay(2000).ConfigureAwait(false);
    }
    
    public bool DoThings() {
    }
    

    带有一些错误处理

    while(true) {
       try {
          if(DoThings()) break;
       }
       catch( XXX ex ) {
          log
       }
       await Task.Delay(2000).ConfigureAwait(false);
    }
    
    public bool DoThings() {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 2015-12-17
      • 2015-09-08
      • 1970-01-01
      相关资源
      最近更新 更多