Stephen Patten
Stephen Patten

Reputation: 6363

How to enable or disable a Polly Policy at run-time?

In the definition of a policy, I'd like to be able to disable or enable the policy at run-time, versus doing it in the call site, since I may have multiple call sites.

This is my approach so far?

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

But alas, this does not compile :)

Thank you, Stephen

Upvotes: 3

Views: 1833

Answers (1)

xcskilab
xcskilab

Reputation: 188

You could return a Policy like this:

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

This use it like this:

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

Upvotes: 5

Related Questions