Retry in exception handler - CSharp Custom Type

CSharp examples for Custom Type:Exception

Description

Retry in exception handler

Demo Code

using System;/*from w  ww. ja  va2 s. c om*/
using System.ComponentModel;
using System.Threading;
class SimpleRetry
{
   static T Retry<T>(Func<T> operation, int attempts)
   {
      while (true)
      {
         try
         {
            attempts--;
            return operation();
         }
         catch (Exception e) when (attempts > 0)
         {
            Console.WriteLine($"Failed: {e}");
            Console.WriteLine($"Attempts left: {attempts}");
            Thread.Sleep(5000);
         }
      }
   }
   static void Main()
   {
      Func<DateTime> temporamentalCall = () =>
      {
         DateTime utcNow = DateTime.UtcNow;
         if (utcNow.Second < 20)
         {
            throw new Exception("test");
         }
         return utcNow;
      };
      var result = Retry(temporamentalCall, 3);
      Console.WriteLine(result);
   }
}

Result


Related Tutorials