如何用 C# 编写重试逻辑?

csharpserver side programmingprogramming更新于 2025/6/28 1:07:17

每当操作失败时都会执行重试逻辑。仅在了解失败操作的完整上下文的情况下才执行重试逻辑。

记录所有导致重试的连接故障非常重要,这样才能识别应用程序、服务或资源的根本问题。

示例

class Program{
   public static void Main(){
      HttpClient client = new HttpClient();
      dynamic res = null;
      var retryAttempts = 3;
      var delay = TimeSpan.FromSeconds(2);
      RetryHelper.Retry(retryAttempts, delay, () =>{
         res = client.GetAsync("https://example22.com/api/cycles/1");
      });
      Console.ReadLine();
   }
}
public static class RetryHelper{
   public static void Retry(int times, TimeSpan delay, Action operation){
      var attempts = 0;
      do{
         try{
            attempts++;
            System.Console.WriteLine(attempts);
            operation();
            break;
         }
         catch (Exception ex){
            if (attempts == times)
               throw;
            Task.Delay(delay).Wait();
         }
      } while (true);
   }
}

相关文章