我正在努力使超时策略正常工作。在集成api时,我有以下需求。
对于这个任务,我想使用Polly,这在我看来是一个非常棒的组件,可以帮助处理短暂的故障。然而,由于我对这一技术非常陌生,我只想确定我是否正确地实现了。
首先,我为Polly创建了这样一个超时策略
var timeoutPolicy =
Policy.TimeoutAsync(
TimeSpan.FromSeconds( 20 ),
TimeoutStrategy.Optimistic,
async ( context, timespan, task ) => {
//write here the cancel request
} );在那之后,我准备执行这个政策。
var policyResult = await timeoutPolicy.ExecuteAndCaptureAsync( async () => {
//make here the request 1
} );我从文档中得到的是,如果timeoutPolicy.ExecuteAndCaptureAsync委托内部发生超时,Polly会自动调用onTimeout委托。对吗?
然而,我的问题是:
发布于 2017-04-14 19:01:14
我从文档中得到的是,如果ExecuteAndCaptureAsync委托内部发生超时,Polly会自动调用onTimeout委托。对吗?
如果在execute委托内部发生异常,会发生什么情况?
因为您使用的是ExecuteAndCaptureAsync(.),所以例外是放在policyResult.FinalException中。
我应该把那个波莉构造包在一个尝试的陷阱里吗?
因为您使用的是ExecuteAndCaptureAsync(..),所以异常被放置在policyResult.FinalException中,因此不需要尝试捕获。
在分析策略结果时,如何理解超时是否已经发生?
TimeoutPolicy 抛出TimeoutRejectedException在超时。因为您使用的是ExecuteAndCaptureAsync(.),所以您应该可以在policyResult.FinalException中找到该异常。
几点进一步的评论。使用TimeoutStrategy.Optimisitic,即CancellationToken,您应该使用取消令牌执行一个委托:
var policyResult = await timeoutPolicy.ExecuteAndCaptureAsync(async (ct) => {
//make request 1, in a form which responds to the cancellation token ct
}, userCancellationToken /* CancellationToken.None is acceptable. Polly will merge its timing-out CancellationToken into ct, during policy execution. */
);其次,作为在onRetryAsync: async ( context, timespan, task ) => { ... }中调用cancel请求的替代方法,您可以选择使用如下模式使代码更有序/更少嵌套:
var policyResult = await timeoutPolicy.ExecuteAndCaptureAsync(async (ct) => {
//make request 1, in a form which responds to the cancellation token ct
}, CancellationToken.None);
if (policyResult.Outcome == OutcomeType.Failure && policyResult.FinalException is TimeoutRejectedException)
{
//write here the cancel request
}UPDATE:调用cancel请求将以任何方式工作--从onRetryAsync内部调用,或者按顺序执行,如上面所示。顺序版本的一个优点是,如果取消请求在异常情况下失败,则可能更容易对发生的情况进行推理。使用嵌套方法(在onRetryAsync中调用cancel请求),最终捕获到policyResult.FinalException中的异常可能来自初始请求或取消请求--而且很难判断哪个异常。
https://stackoverflow.com/questions/43416878
复制相似问题