首页 / C# / c# – Polly超时政策澄清
c# – Polly超时政策澄清
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – Polly超时政策澄清,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2795字,纯文字阅读大概需要4分钟。
内容图文
我试图让timout政策正常工作.
在集成api时我有以下要求.
>创建一个http请求以调用endpoint1并传递transactionID并捕获结果
>如果http请求在20秒内没有回答,则发送具有相同transactionID的取消请求并捕获结果
对于这项任务,我想使用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委托内发生了一个timout,Polly会自动调用onTimeout委托.对?
不过我的问题是:
>如果在执行委托内发生异常,会发生什么?我应该将这个polly构造包装在try catch中吗?
>当我分析政策结果时,我如何理解超时是否发生?
解决方法:
What I got from the documentation is that if a timeout occurs inside the
ExecuteAndCaptureAsync delegate Polly automagically invoke the
onTimeout delegate. Right?
What happens if inside the execute delegate an exception occurs?
因为您使用的是ExecuteAndCaptureAsync(…),所以例外是placed in policyResult.FinalException.
Should I wrap that polly construct in a try catch?
因为您正在使用ExecuteAndCaptureAsync(..),所以异常放在policyResult.FinalException中,因此您不需要try-catch.
When I analyze the policy result how do I understand if the timeout has happened or not?
TimeoutPolicy throws TimeoutRejectedException超时.因为您正在使用ExecuteAndCaptureAsync(…),所以您应该在policyResult.FinalException中找到该异常.
还有一些评论.使用TimeoutStrategy.Optimisitic,即based on co-operative cancellation by 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)=> {…},您可以选择使用下面的模式使代码更顺序/更少嵌套:
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
}
更新:调用取消请求将以任何方式工作 – 从onRetryAsync内部,或顺序,如上所述.顺序版本的一个优点是,如果取消请求因异常而失败,它可以更容易推断出现的情况.使用嵌套方法(在onRetryAsync中调用取消请求),最终捕获到policyResult.FinalException中的异常可能来自初始请求或取消请求 – 并且可能很难分辨哪个.
内容总结
以上是互联网集市为您收集整理的c# – Polly超时政策澄清全部内容,希望文章能够帮你解决c# – Polly超时政策澄清所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。