如何在运行时启用或禁用 Polly 策略?

Ste*_*ten 3 c# polly

在策略的定义中,我希望能够在运行时禁用或启用策略,而不是在调用站点中执行此操作,因为我可能有多个调用站点。

这是我到目前为止的做法吗?

private RetryPolicy<IDisposable> GetRetryPolicy()
{
    if (!this.config.DistributedLockEnabled)
    {
        NoOpPolicy<IDisposable> policy = Policy.NoOp<IDisposable>();
        return policy;
    }

    RetryPolicy<IDisposable> lockPolicy = Policy
        .Handle<TimeoutException>()
        .OrResult<IDisposable>(d => d == null)
        .WaitAndRetry(
            this.config.WorkflowLockHandleRequestRetryAttempts,
            attempt => TimeSpan.FromSeconds(this.config.WorkflowLockHandleRequestRetryMultiplier * Math.Pow(this.config.WorkflowLockHandleRequestRetryBase, attempt)),
            (delegateResult, calculatedWaitDuration, attempt, context) =>
                {
                    if (delegateResult.Exception != null)
                    {
                        this.logger.Information(
                            "Exception {0} attempt {1} delaying for {2}ms",
                            delegateResult.Exception.Message,
                            attempt,
                            calculatedWaitDuration.TotalMilliseconds);
                    }
                });
    return lockPolicy;
}
Run Code Online (Sandbox Code Playgroud)

但可惜的是,这不能编译:)

谢谢你,斯蒂芬

xcs*_*lab 5

您可以返回这样的策略:

private static Policy GetRetryPolicy(bool useWaitAndRetry)
    {
        if (!useWaitAndRetry)
        {
            return Policy.NoOp();
        }

        return Policy
            .Handle<Exception>()
            .WaitAndRetry(new[]
            {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(3)
            });
    }
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

GetRetryPolicy(true).Execute(() =>
            {
                // Process the task here
            });
Run Code Online (Sandbox Code Playgroud)

  • x-ref 还在 https://github.com/App-vNext/Polly/issues/634 进行了讨论。将策略作为接口返回也是一个选项:`private ISyncPolicy&lt;IDisposable&gt; GetRetryPolicy() { ... }` (2认同)