Polly: C# library for retry and resilience

When using an external system, perhaps through HTTP calls, it is possible that the call fails and it is necessary to repeat it. This can happen when the system that accepts calls is overloaded or is not able to give an answer immediately but by trying again the answer can be obtained.
To perform this action in C# there is a library that allows you to satisfy this requirement in an elegant way and with very few lines of code. This library is called Polly. At the following link I have created a repository where I compare a method for retrying with and without Polly.

My GitHub repo: https://github.com/MaverickFP/TestPolly

I have created a singleton class named Service which has a method which, every time it is invoked, throws an exception of the type NotImplementedException. This class simulates an external system that returns an error.

        --Part of Service Class
        /// <summary>
        /// Fake method that throws an exception. The number of times it is invoked is counted.
        /// </summary>
        /// <exception cref="NotImplementedException">Exeception</exception>
        public void doOperation()
        {
            counterInvoke++;
            Console.WriteLine("Num of invoke: " + counterInvoke);
            throw new NotImplementedException("Not implemented method");
        }

The Client class is used to invoke the doOperation method of the service class.
Without Polly, a method similar to the following must be implemented for the retry with a while and a try – catch inside.

         /// <summary>
        /// Call Service.doOperation without Polly
        /// </summary>
        public void callSomethingOld()
        {
            bool inError = true;
            while (inError)
            {
                try
                {
                    serviceClass.doOperation();
                    inError = false;
                }
                catch (NotImplementedException ex)
                {
                    inError = true;
                }
            }
        }

Using Polly the code becomes much more readable and elegant. First you need to use the Polly and Polly.Contrib.WaitAndRetry libraries.

To use Polly in the simplest and fastest way, you need to define a policy which specifies the type of exception on which you need to retry. Then you have to specify how to retry, whether to use only a number of retries (Retry) or wait before retrying (WaitAndRetry) and whether the wait time should be an exponential backoff (Backoff.DecorrelatedJitterBackoffV2).

//Policy definition
RetryPolicy policy = Policy.Handle<NotImplementedException>().Retry(5);

//Apply policy to method call
PolicyResult policyResult = policy.ExecuteAndCapture(() => serviceClass.doOperation());

Lascia un commento