1

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

ABS
  • 2,626
  • 3
  • 28
  • 44
  • 2
    Related: [Exception User-Unhandled reported in VS Debugger when using Polly](https://stackoverflow.com/questions/44057939/exception-user-unhandled-reported-in-vs-debugger-when-using-polly). Isn't it wonderful when instead of debugging your program, you end up debugging the debugger? Ctrl+F5 for the win! – Theodor Zoulias Mar 13 '21 at 13:03

1 Answers1

4

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

dotnetstep
  • 17,065
  • 5
  • 54
  • 72
  • So useful NOTE! Both of mine and yours code stops in debug mode and I really don't can understand it why?! – ABS Mar 13 '21 at 11:11
  • Your edit obliged me to approve your answer. Now it is clear to me why ExecuteAsync works great(because it runs Do on a separate thread) – ABS Mar 13 '21 at 12:07