gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:20:09 30 4
gpt4 key购买 nike

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

这是我目前的方法?

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

但是,唉,这不编译:)

谢谢,斯蒂芬

最佳答案

您可以返回这样的政策:

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

关于c# - 如何在运行时启用或禁用 Polly 策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55779085/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com