How to write retry logic in C#?


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

Updated on: 19-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements