【发布时间】:2022-10-19 13:51:28
【问题描述】:
我们开始在我们遗留的 WinForms 项目中使用 Polly 库,该项目仍然在 .NET 4.0 框架上运行(这是必需的)。
问题是我们必须使用 Polly 库的 4.3 版本,并且很难找到问题的解决方案,因为我们找到的所有文档都是关于该库的更新版本。
例如,我们不能从重试回调传递Context 值来执行,因为Context 是只读的,我们不能传递参数来执行委托,因为它使用Action 类型。
对于所有这些问题,我们已经找到了创造性的解决方案,但我们仍然无法找到在特定条件下停止执行的方法。
在 Polly 5 中,为此目的引入了CancellationToken,但我想在以前的版本中也有办法强制停止重试。
public RetryPolicy DevicePolicy => Policy
.Handle<Exception>()
.WaitAndRetry(
MaxRetries,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(exception, timeSpan, retryCount, context) =>
{
//If i get the timeout exception i want to stop the execution
if (exception is TimeoutException)
{
//In Polly 5.0 I can set the cancellationToken but with 4.3 there isn't
var cts = context["CancellationTokenSource"] as CancellationTokenSource;
cts.Cancel();
}
else
{
var errHeader = $"device connection error. Attempt {retryCount} of {MaxRetries}";
Log.Warn(errHeader, exception);
}
});
任何想法?
【问题讨论】:
标签: c# .net-4.0 polly cancellation-token retry-logic