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

时间:2019-04-21 01:13:22

标签: 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;
}

但是a,这不能编译:)

谢谢你, 斯蒂芬

1 个答案:

答案 0 :(得分:0)

您可以返回以下政策:

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

这样使用它:

GetRetryPolicy(true).Execute(() =>
            {
                // Process the task here
            });