ABS
ABS

Reputation: 2803

Polly synchronous Retry

I just be familiar with Polly and I'm trying to start with a simple Retry mechanism.

Here's the code:

static void Main(string[] args)
{
        Policy
            .Handle<NotImplementedException>()
            .WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(100), (exception, i, arg3) => Console.WriteLine(i))
            .Execute(() => { Console.WriteLine(Do()); });
}

private static string Do()
{
    return ++_counter < 3
        ? throw new NotImplementedException()
        : "done";
    }
}

I expected that the thrown NotImplementedException caught by Polly and retried until desired result return. But at first exception raised the program stops! Where did I make a mistake? Thanks in advance

Upvotes: 1

Views: 1607

Answers (1)

dotnetstep
dotnetstep

Reputation: 17485

If I have to do same thing I can do following way.

class Program
    {
        static int _counter = 0;
        static void Main(string[] args)
        {
            Console.WriteLine(Policy
           .Handle<NotImplementedException>()
           .WaitAndRetry(3, retryAttempt => TimeSpan.FromMilliseconds(100), (exception, i, arg3) => Console.WriteLine(i))
           .Execute<string>(() => Do()));
            Console.ReadLine();
        }
        private static string Do()
        {
            Console.WriteLine(_counter);
            return ++_counter < 3
                ? throw new NotImplementedException()
                : "done";
        }
    }

Explanation:

In your code you are trying to do Console.WriteLine inside Execute, it throw exception so Console.WriteLine not able to handle that things. Actually you have to execute Do method and expect success result and that handle by Console.WriteLine as it will be string.

Note : I still feel that your code is fine too. Try to execute that from console instead of debug.

Your code not working in debug mode due to following settings. Uncheck this checkbox.

enter image description here

Upvotes: 4

Related Questions