How to write retry logic in C#?

CsharpServer Side ProgrammingProgramming

Retry logic is implemented whenever there is a failing operation. Implement retry logic only where the full context of a failing operation.

It's important to log all connectivity failures that cause a retry so that underlying problems with the application, services, or resources can be identified.

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);
   }
}
raja
Published on 19-Aug-2020 17:08:15
Advertisements