如何在第一次和每次重试时执行一个方法?

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

我正在使用 Polly 重试策略:

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());

通过上述,FirstAndRetryMethodRetry 上按预期调用。我如何在第一次执行 DoSomething 时调用它?

重试策略定义了一个 onRetry 可选委托,它在尝试失败之后但在等待持续时间(所谓的惩罚)之前调用。

因此,假设您有以下 FirstAndRetryMethodDoSomething 的实现用于调试目的:

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 { ... };
}

然后输出将如下所示:

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

因为您定义了 3 个时间戳,所以您的重试次数为 3。

  • 您有一次初始尝试和 3 次重试(总共 4 次)(DoSomething has been called for the ...)
  • 和 3 个 onRetry 调用(FirstAndRetryMethod has been called for the ...)。

如果你想确保在每次尝试(包括初始)之前调用 FirstAndRetryMethod 那么你应该在 Execute 委托中调用它:

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

您应该删除策略定义的 onRetry 部分。

然后输出将如下所示:

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

现在您有 4 个 FirstAndRetryMethod 和 4 个 DoSomething 调用。