Home  >  Article  >  Backend Development  >  How to write retry logic in C#?

How to write retry logic in C#?

王林
王林forward
2023-09-24 12:45:031364browse

How to write retry logic in C#?

As long as the operation fails, retry logic will be implemented. Implement retries Only document logic within the full context of the failed operation.

It is important to log all connection failures that result in retries so that the underlying Can identify problems with applications, services, or resources.

Example

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);
   }
}

The above is the detailed content of How to write retry logic in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete