卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章21569本站已运行3415

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

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

只要操作失败,就会实现重试逻辑。实施重试 仅在失败操作的完整上下文中记录逻辑。

记录导致重试的所有连接故障非常重要,以便底层 可以识别应用程序、服务或资源的问题。

示例

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);
   }
}
卓越飞翔博客
上一篇: 如何在在线答题中实现试卷的自动分发和自动纠错
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏