Polly策略重试结果条件和异常包装器c#



Polly框架的包装器,使实现可以停留在一个位置

我能够基于上面的链接创建一个包装器。但我不确定如何才能使它成为通用的。我想要这个包装器来进行不仅仅是结果的布尔检查,比如处理异常。

这是我的代码:

public class RetryWrapper
{
public static bool Execute(Func<bool> func)
{
RetryPolicy<bool> retryPolicyNeedsTrueResponse =
Policy.HandleResult<bool>(b => b != true)
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(15)
});
return retryPolicyNeedsTrueResponse.Execute(func);
}
}

非常感谢您的帮助。提前感谢

为了使其通用,我想你可以做一些类似的事情

public static T Execute<T>(Func<T> func, Func<T,bool> success)
{
RetryPolicy<T> retryPolicyNeedsTrueResponse =
Policy.HandleResult<T>(b => success(T))
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(15)
});
return retryPolicyNeedsTrueResponse.Execute(func);
}

注意:这样做的好处似乎是不确定的,充其量也是可疑的,而且您还需要async的另一个版本。

您可能只需要处理一系列时间跨度,重用它,并让您的代码更具声明性,更能适应polly的所有其他功能。

注意2:这是完全未经测试的

最新更新