[英]Enter a Catch Method in WaitAndRetryAsync
目标:
如果你已经尝试了第三次,但它没有成功。 然后你想使用另一种方法。
我想防止显示错误消息网页。
问题:
是否可以在 WaitAndRetryAsync 中输入与 catch 方法类似的方法?
RetryPolicy<HttpResponseMesssage> httpWaitAndRetryPolicy = Policy
.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync
(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2. retryAttempt)/2));
谢谢!
您可以在策略上使用ExecuteAsync
,然后使用ContinueWith
来处理最终响应,如下所示:
RetryPolicy<HttpResponseMessage>
.Handle<HttpRequestException>()
.Or<TaskCanceledException>()
.WaitAndRetryAsync
(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt) / 2))
.ExecuteAsync(() =>
{
//do stuff that you want retry
}).ContinueWith(x =>
{
if (x.Exception != null)
{
//means exception raised during execute and handle it
}
// return your HttpResponseMessage
}, scheduler: TaskScheduler.Default);
遵循@TheodorZoulias 的评论,使用ContinueWith
的最佳实践是将TaskScheduler
显式设置为默认值,因为ContinueWith
将调度程序更改为Current
并可能导致死锁。
首先, WaitAndRetryAsync
返回AsyncRetryPolicy<T>
,而不是RetryPolicy<T>
,这意味着您发布的代码无法编译。
在 polly 的情况下,策略的定义和该策略的执行是分开的。 因此,首先您定义一个策略(或策略的混合),然后在需要时执行它。
AsyncRetryPolicy<HttpResponseMessage> retryInCaseOfNotSuccessResponsePolicy = Policy
.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync
(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2.retryAttempt) / 2));
HttpResponseMessage serviceResponse = null;
try
{
serviceResponse = await retryInCaseOfNotSuccessResponsePolicy.ExecuteAsync(
async ct => await httpClient.GetAsync(resourceUri, ct), default);
}
catch (Exception ex)
when(ex is HttpRequestException || ex is OperationCanceledException)
{
//TODO: log
}
if (serviceResponse == null)
{
//TODO: log
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.