What am I missing in this that Polly is not retrying my action?

3.8k views Asked by At
public class PollyTest
{
    public void RunWithPolly()
    {
        Console.WriteLine("RunWithPolly invoked...");
        int zero = 0;
        int result= 10 / zero;
    }
}

And in my Main function I create a Policy as below:

var retryPolicy = Policy.Handle<DivideByZeroException>().Retry(3);
PollyTest pollyTest = new PollyTest();
retryPolicy.Execute(() => pollyTest.RunWithPolly());

When I execute this, it always fails with unhandled exception error inside function RunWithPolly on the very first run itself.

1

There are 1 answers

0
mountain traveller On BEST ANSWER

TL;DR You were just seeing the VS debugger breaking on exceptions.

Re:

When I execute this, it always fails with unhandled exception error inside function "RunWithPolly" on the very first run itself

What you were seeing was not Polly or the execution failing. You were just seeing the debugger breaking on the DivideByZeroException thrown (to show it to you, before you decide whether/how to continue the execution using the debugger controls).

Re:

Annotating the method RunWithPolly with DebuggerStepThrough attribute resolved the problem

This didn't change or 'fix' anything about the execution. It simply stopped the debugger breaking on the exception, making it perhaps look as if something was operating differently.

To verify this to yourself, you could declare your Polly policy instead as:

var retryPolicy = Policy
    .Handle<DivideByZeroException>()
    .Retry(3,
        (ex, i) => { Console.Writeline($"Making retry {i} due to {ex.Message}."); }
    );

Run your example then without the debugger and you will see all the retries being made. Run it with the debugger and without the [DebuggerStepThrough] attribute, just press F5/debugger-continue each time the debugger breaks, and you will again see the code correctly work through all the retries. The [DebuggerStepThrough] makes no difference to the execution, just to what you see in the debugger.


This StackOverflow q/a describes the identical scenario.

The Polly wiki describes in detail why this happens, what the VS debugger means by a 'user-unhandled' exception, why this can be confusing, and options to configure various versions of Visual Studio to reduce this debugging noise.