Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16310

How to execute a method the first time and on each retry?

I'm using Polly for a retry policy:

var policy = Policy
    .Handle<DatabaseException>(x => x.DatabaseErrors.ContainsKey(2601))
    .WaitAndRetry(new[]
    {
        TimeSpan.FromMilliseconds(500),
        TimeSpan.FromMilliseconds(1000),
        TimeSpan.FromMilliseconds(1500)
    }, (exception, timeSpan) => {
        FirstAndRetryMethod();
    });

policy = Policy.Excecute(() => DoSomething());

With the above, FirstAndRetryMethod is called as expected on Retry. How can I call this also the first time DoSomething is executed?

Upvotes: 1

Views: 87

Answers (1)

Peter Csala
Peter Csala

Reputation: 22819

The Retry policy defines an onRetry optional delegate which is called after the failed attempt but before the wait duration (so called penalty).

So, lets suppose you have the following implementations for FirstAndRetryMethod and DoSomething for debugging purposes:

static int onretryCallCount = 0;
static void FirstAndRetryMethod() {
    Console.WriteLine("FirstAndRetryMethod has been called for the " + onretryCallCount++ + "th time");
}

static int doSomethingCallCount = 0;
static void DoSomething() {
    Console.WriteLine("DoSomething has been called for the " + doSomethingCallCount++ + "th time");
    throw new DatabaseException { ... };
}

Then the output will look like this:

DoSomething has been called for the 0th time
FirstAndRetryMethod has been called for the 0th time
DoSomething has been called for the 1th time
FirstAndRetryMethod has been called for the 1th time
DoSomething has been called for the 2th time
FirstAndRetryMethod has been called for the 2th time
DoSomething has been called for the 3th time

Because you have defined 3 timestamps that's why your retry count is 3.

  • You have an initial attempt and 3 retries (4 in total) (DoSomething has been called for the ...)
  • and 3 onRetry calls (FirstAndRetryMethod has been called for the ...).

If you want to make sure that FirstAndRetryMethod is called prior each and every attempt (including the initial) then you should call it inside the Execute delegate:

policy.Execute(() => { FirstAndRetryMethod(); DoSomething(); });

and you should delete the onRetry part of your policy definition.

Then the output will look like this:

FirstAndRetryMethod has been called for the 0th time
DoSomething has been called for the 0th time
FirstAndRetryMethod has been called for the 1th time
DoSomething has been called for the 1th times
FirstAndRetryMethod has been called for the 2th time
DoSomething has been called for the 2th time
FirstAndRetryMethod has been called for the 3th time
DoSomething has been called for the 3th time

Now you have 4 FirstAndRetryMethod and 4 DoSomething calls.

Upvotes: 2

Related Questions