Polly – exception handling policies

Sometimes we want to repeat attempt after first unsuccessful attempt. Sometimes when we get exception it is timeout or something like that. So, we could repeat again and maybe we do what we want. I think that you can use Polly for it.

You can create event handling polices by Polly and repeat attempets if you want. First of all you have to install Polly by NuGet:

PM> Install-Package Polly

And simple example:
using Polly;
using System;
 
namespace PollyExample
{
    class Program
    {
        static int divider = 0;
 
        static void Main(string[] args)
        {
            var policy = Policy
                            .Handle()
                            .WaitAndRetry(
                                5,
                                retryAttempt => TimeSpan.FromSeconds(2),
                                (exception, timeSpan, context) =>
                                    {
                                        Console.WriteLine("I can't do that. I'm waiting for next attempt.");
                                    });
            try
            {
                policy.Execute(() => test());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
 
            Console.ReadKey();
        }
 
        static void test()
        {
            int result = 100/divider;
        }
    }
}

How you can see below we’ve tried 5 times divide and after that catch handles exception:

And now I’m changing divider after first attempt:
using Polly;
using System;
 
namespace PollyExample
{
    class Program
    {
        static int divider = 0;
 
        static void Main(string[] args)
        {
            var policy = Policy
                            .Handle()
                            .WaitAndRetry(
                                5,
                                retryAttempt => TimeSpan.FromSeconds(2),
                                (exception, timeSpan, context) =>
                                    {
                                        Console.WriteLine("I can't do that. I'm waiting for next attempt.");
                                        divider++;
                                    });
            try
            {
                policy.Execute(() => test());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
 
            Console.ReadKey();
        }
 
        static void test()
        {
            int result = 100/divider;
            Console.WriteLine(result);
        }
    }
}

And now it looks better: