How to write retry logic in C#?

王林
Release: 2023-09-24 12:45:03
forward
1366 people have browsed it

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);
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template