Search code examples
c#async-awaitpollyretry-logic

C# Polly WaitAndRetry policy for function retry


I'm very new to C# coding and I just want to know how to setup polly WaitAndRetry for my function if it failed. Following is my steps

  1. I installed package Install-Package Polly, using NuGet package
  2. added using polly in my code.
  3. Below is my code
public async Task<string> ConfigInsert(config model)
{
    try
    {
        SendToDatabase(model);

        await Policy.Handle<Exception>()
            .RetryAsync(NUMBER_OF_RETRIES)
            .ExecuteAsync(async () =>
                await SendToDatabase(model))
            .ConfigureAwait(false);
    } 
    Catch(Exception e)
    {
        _log.write("error occurred");
    }
        
    public async Task<string> SendToDataBase(config model)
    {
        var ss = DataBase.PostCallAsync(model)
            .GetAwaiter()
            .GetResult();
        return ss;
    }
}

But this call is continuously calling without any delay. I tried to use WaitAndRetryAsync in catch call but it's not working. WaitAndRetryAsync accepts only HTTP repose message. I want to implement ait and retry option in try-catch


Solution

  • You say you want WaitAndRetry but you don't use that function... And it doesn't only work with HttpResponse. Please read the documentation.

    The code below should give you a head start:

    class Program
    {
        static async Task Main(string[] args)
        {
            // define the policy using WaitAndRetry (try 3 times, waiting an increasing numer of seconds if exception is thrown)
            var policy = Policy
              .Handle<Exception>()
              .WaitAndRetryAsync(new[]
              {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(3)
              });
    
            // execute the policy
            await policy.ExecuteAsync(async () => await SendToDatabase());
    
        }
    
        static async Task SendToDatabase()
        {
            Console.WriteLine("trying to send to database");
            await Task.Delay(100);
            throw new Exception("it failed!");
        }
    }