在策略的定义中,我希望能够在运行时禁用或启用策略,而不是在调用站点中执行此操作,因为我可能有多个调用站点。
这是我到目前为止的做法吗?
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)
但可惜的是,这不能编译:)
谢谢你,斯蒂芬
您可以返回这样的策略:
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)
| 归档时间: |
|
| 查看次数: |
1481 次 |
| 最近记录: |