- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试合并 TimeoutPolicy
和 RetryPolicy
对于在 Func
中完成的 API 调用,但我没有找到实现此目标的方法。
如果我只使用 RetryPolicy
, 它工作正常。
我有一个 GetRequest
调用 HttpClient
的方法并返回数据:
async Task<Data> GetRequest(string api, int id)
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync($"{api}{id}");
var rawResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Data>(rawResponse);
}
我还有 Func
这将嵌入对此方法的调用: var func = new Func<Task<Data>>(() => GetRequest(api, i));
我这样调用服务: Results.Add(await _networkService.RetryWithoutTimeout<Data>(func, 3, OnRetry));
这RetryWithoutTimeout
方法是这样的:
async Task<T> RetryWithoutTimeout<T>(Func<Task<T>> func, int retryCount = 1, Func<Exception, int, Task> onRetry = null)
{
var onRetryInner = new Func<Exception, int, Task>((e, i) =>
{
return Task.Factory.StartNew(() => {
#if DEBUG
System.Diagnostics.Debug.WriteLine($"Retry #{i} due to exception '{(e.InnerException ?? e).Message}'");
#endif
});
});
return await Policy.Handle<Exception>()
.RetryAsync(retryCount, onRetry ?? onRetryInner)
.ExecuteAsync<T>(func);
}
我已更新此代码以使用 TimeoutPolicy
, 和一个新的 RetryWithTimeout
方法:
async Task<T> RetryWithTimeout<T>(Func<Task<T>> func, int retryCount = 1, Func<Exception, int, Task> onRetry = null, int timeoutDelay = 30)
{
var onRetryInner = new Func<Exception, int, Task>((e, i) =>
{
return Task.Factory.StartNew(() => {
#if DEBUG
System.Diagnostics.Debug.WriteLine($"Retry #{i} due to exception '{(e.InnerException ?? e).Message}'");
#endif
});
});
var retryPolicy = Policy
.Handle<Exception>()
.RetryAsync(retryCount, onRetry ?? onRetryInner);
var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromSeconds(timeoutDelay));
var policyWrap = timeoutPolicy.WrapAsync((IAsyncPolicy)retryPolicy);
return await policyWrap.ExecuteAsync(
async ct => await Task.Run(func),
CancellationToken.None
);
}
但我不知道如何管理 GetRequest()
方法:我所有的测试都失败了...
编辑:我根据@Peter Csala 的评论创建了一个示例。
所以首先,我刚刚更新了重试次数以检查retryPolicy
是否成功。已正确应用:
private const int TimeoutInMilliseconds = 2500;
private const int MaxRetries = 3;
private static int _times;
static async Task Main(string[] args)
{
try
{
await RetryWithTimeout(TestStrategy, MaxRetries);
}
catch (Exception ex)
{
WriteLine($"{nameof(Main)} - Exception - Failed due to: {ex.Message}");
}
Console.ReadKey();
}
private static async Task<string> TestStrategy(CancellationToken ct)
{
WriteLine($"{nameof(TestStrategy)} has been called for the {_times++}th times.");
await Task.Delay(TimeoutInMilliseconds * 2, ct);
return "Finished";
}
internal static async Task<T> RetryWithTimeout<T>(Func<CancellationToken, Task<T>> func, int retryCount = 1, Func<Exception, int, Task> onRetry = null, int timeoutDelay = TimeoutInMilliseconds)
{
WriteLine($"NetworkService - {nameof(RetryWithTimeout)}");
var onRetryInner = new Func<Exception, int, Task>((e, i) =>
{
WriteLine($"NetworkService - {nameof(RetryWithTimeout)} #{i} due to exception '{(e.InnerException ?? e).Message}'");
return Task.CompletedTask;
});
var retryPolicy = Policy
.Handle<Exception>()
.RetryAsync(retryCount, onRetry ?? onRetryInner);
var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromMilliseconds(timeoutDelay));
var policyWrap = Policy.WrapAsync(retryPolicy, timeoutPolicy); //Important part #1
return await policyWrap.ExecuteAsync(
async ct => await func(ct), //Important part #2
CancellationToken.None);
}
关于日志,情况很好:
NetworkService - RetryWithTimeout
TestStrategy has been called for the 0th times.
NetworkService - RetryWithTimeout - Retry #1 due to exception 'A task was canceled.'
TestStrategy has been called for the 1th times.
NetworkService - RetryWithTimeout - Retry #2 due to exception 'A task was canceled.'
TestStrategy has been called for the 2th times.
NetworkService - RetryWithTimeout - Retry #3 due to exception 'A task was canceled.'
TestStrategy has been called for the 3th times.
Main - TimeoutRejectedException - Failed due to: The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.
然后,我改变了policyWrap
因为我需要一个全局超时:
private static async Task<string> TestStrategy(CancellationToken ct)
{
WriteLine($"{nameof(TestStrategy)} has been called for the {_times++}th times.");
await Task.Delay(1500, ct);
throw new Exception("simulate Exception");
}
var policyWrap = timeoutPolicy.WrapAsync(retryPolicy);
关于日志,也是正确的:
TestStrategy has been called for the 0th times.
NetworkService - RetryWithTimeout #1 due to exception 'simulate Exception'
TestStrategy has been called for the 1th times.
NetworkService - RetryWithTimeout #2 due to exception 'A task was canceled.'
Main - TimeoutRejectedException - Failed due to: The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.
在那之后,我实现了一个调用 API 的方法,其中有一些 Exceptions
, 更接近我的需要:
static async Task Main(string[] args)
{
try
{
await RetryWithTimeout(GetClientAsync, MaxRetries);
}
catch (TimeoutRejectedException trEx)
{
WriteLine($"{nameof(Main)} - TimeoutRejectedException - Failed due to: {trEx.Message}");
}
catch (WebException wEx)
{
WriteLine($"{nameof(Main)} - WebException - Failed due to: {wEx.Message}");
}
catch (Exception ex)
{
WriteLine($"{nameof(Main)} - Exception - Failed due to: {ex.Message}");
}
Console.ReadKey();
}
private static async Task<CountriesResponse> GetClientAsync(CancellationToken ct)
{
WriteLine($"{nameof(GetClientAsync)} has been called for the {_times++}th times.");
HttpClient _client = new HttpClient();
try
{
var response = await _client.GetAsync(apiUri, ct);
// ! The server response is faked through a Proxy and returns 500 answer !
if (!response.IsSuccessStatusCode)
{
WriteLine($"{nameof(GetClientAsync)} - !response.IsSuccessStatusCode");
throw new WebException($"No success status code {response.StatusCode}");
}
var rawResponse = await response.Content.ReadAsStringAsync();
WriteLine($"{nameof(GetClientAsync)} - Finished");
return JsonConvert.DeserializeObject<CountriesResponse>(rawResponse);
}
catch (TimeoutRejectedException trEx)
{
WriteLine($"{nameof(GetClientAsync)} - TimeoutRejectedException : {trEx.Message}");
throw trEx;
}
catch (WebException wEx)
{
WriteLine($"{nameof(GetClientAsync)} - WebException: {wEx.Message}");
throw wEx;
}
catch (Exception ex)
{
WriteLine($"{nameof(GetClientAsync)} - other exception: {ex.Message}");
throw ex;
}
}
日志仍然正确:
NetworkService - RetryWithTimeout
GetClientAsync has been called for the 0th times.
GetClientAsync - !response.IsSuccessStatusCode
GetClientAsync - WebException: No success status code InternalServerError
NetworkService - RetryWithTimeout #1 due to exception 'No success status code InternalServerError'
GetClientAsync has been called for the 1th times.
GetClientAsync - !response.IsSuccessStatusCode
GetClientAsync - WebException: No success status code InternalServerError
NetworkService - RetryWithTimeout #2 due to exception 'No success status code InternalServerError'
GetClientAsync has been called for the 2th times.
GetClientAsync - !response.IsSuccessStatusCode
GetClientAsync - WebException: No success status code InternalServerError
NetworkService - RetryWithTimeout #3 due to exception 'No success status code InternalServerError'
GetClientAsync has been called for the 3th times.
GetClientAsync - other exception: The operation was canceled.
Main - TimeoutRejectedException - Failed due to: The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.
最后,我希望能够调用一个“通用”方法,我可以为每个 API 调用重用该方法。这个方法将是这样的:
static async Task<T> ProcessGetRequest<T>(Uri uri, CancellationToken ct)
{
WriteLine("ApiService - ProcessGetRequest()");
HttpClient _client = new HttpClient();
var response = await _client.GetAsync(uri);
if (!response.IsSuccessStatusCode)
{
WriteLine("ApiService - ProcessGetRequest() - !response.IsSuccessStatusCode");
throw new WebException($"No success status code {response.StatusCode}");
}
var rawResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(rawResponse);
}
但是为此,我必须同时通过 CancellationToken
和 API Uri
通过RetryWithTimeout
我不知道如何管理它。
我尝试更改 RetryWithTimeout
的签名通过类似的东西:
internal static async Task<T> RetryWithTimeout<T>(Func<Uri, CancellationToken, Task<T>> func, int retryCount = 1, Func<Exception, int, Task> onRetry = null, int timeoutDelay = TimeoutInMilliseconds)
但我找不到如何管理 Func
...
您有什么想法或解释吗?
最佳答案
需要将CancellationToken
传递给待取消(超时)函数。
那么,假设您有以下简化方法:
private const int TimeoutInMilliseconds = 1000;
private static int _times;
private static async Task<string> TestStrategy(CancellationToken ct)
{
Console.WriteLine($"{nameof(TestStrategy)} has been called for the {_times++}th times.");
await Task.Delay(TimeoutInMilliseconds * 2, ct);
return "Finished";
}
因此,您的RetryWithTimeout
可以像这样调整/修改:
static async Task<T> RetryWithTimeout<T>(Func<CancellationToken, Task<T>> func, int retryCount = 1, Func<Exception, int, Task> onRetry = null, int timeoutDelay = TimeoutInMilliseconds)
{
var onRetryInner = new Func<Exception, int, Task>((e, i) =>
{
Console.WriteLine($"Retry #{i} due to exception '{(e.InnerException ?? e).Message}'");
return Task.CompletedTask;
});
var retryPolicy = Policy
.Handle<Exception>()
.RetryAsync(retryCount, onRetry ?? onRetryInner);
var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromMilliseconds(timeoutDelay));
var policyWrap = Policy.WrapAsync(retryPolicy, timeoutPolicy); //Important part #1
return await policyWrap.ExecuteAsync(
async ct => await func(ct), //Important part #2
CancellationToken.None);
}
重要部分 #1 - 重试是外层策略,超时是内层策略
重要部分 #2 - 由于超时,CancellationToken 被传递给要取消的函数
下面的用法
static async Task Main(string[] args)
{
try
{
await RetryWithTimeout(TestStrategy);
}
catch (Exception ex)
{
Console.WriteLine($"Failed due to: {ex.Message}");
}
Console.ReadKey();
}
将产生以下输出:
TestStrategy has been called for the 0th times.
Retry #1 due to exception 'A task was canceled.'
TestStrategy has been called for the 1th times.
Failed due to: The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.
请记住,在重试开始之前有第 0 次尝试。
关于c# - Polly:如何结合 TimeoutPolicy 和 RetryPolicy 来请求 Func,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64351478/
我有一张 Excel 表格,用于更新玩家评分。 播放器 配售 初始化 1 2 3 4 金融评级 一个 1 2.0 1.000 0.018 0.016 0.014 2.007 D 2 -2.0 54.5
我有一个 map = std::map ,其中 myItemModel继承QAbstractItemModel . 我现在要合并所有 myItemModel合一myItemModel (其他所有元素模
我大量使用“do.call”来生成函数调用。例如: myfun <- "rnorm"; myargs <- list(n=10, mean=5); do.call(myfun, myargs); 但是
想象一下 InputStream 的以下变体: trait FutureInputStream { //read bytes asynchronously. Empty array means E
这是我的 C 代码: #include void sum(); int newAlphabet; int main(void) { sum();
我只是想选择类“.last”之后的每个元素。 HTML: 1 2 Jquery
我正在为一个项目构建一个 XML 反序列化器,我经常遇到这种类型的代码情况: var myVariable = ParseNDecimal(xml.Element("myElement")) == n
这是来自 Selecting the highest salary 的继续问题 假设有一个表 'wagetable' name lowhours highhours wage pri
我正在为我的程序创建一个战舰程序;该程序运行良好,但我试图确保当用户将坐标超出范围时,程序会说他们输入的坐标不正确。这是代码: #include #include void
我有一个函数,它为每种情况返回不同的 DWORD 值,如果出现错误。所以我有以下定义: #define ERR_NO_DB_CONNECTION 0x90000 #define ERR_DB_N
在派生类中引发基类事件以下简单示例演示了在基类中声明可从派生类引发的事件的标准方法。此模式广泛应用于 .NET Framework 类库中的 Windows 窗体类。在创建可用作其他类的基类的类时,应
我只是想知道这是否可能: use Modern::Perl; my @list = ('a' .. 'j'); map { func($_) } each(@list); sub func { m
我一直在使用 =IF(L2="","Active",IF(K2I2,"Late"))) 有效,但现在我需要检查 F 上的多个条件 专栏 我试过了 OR 函数 =IF(OR(F2="Scheduled"
我有 2 个命令,如下所示。 在视频中添加介绍图片 ffmpeg -y -loop 1 -framerate 10 -t 3 -i intro.png -i video.mp4 -filter_com
好的,我有这个公式可以根据名字和姓氏列表生成用户名。现在,虽然这可行,但我希望单元格改为引用我自己的 VBA 函数。但是,由于代码少得多,我仍然想使用原始公式。 我有这个公式: =SUBSTITUTE
我有两个 HAProxy 实例。两个实例都启用了统计信息并且工作正常。 我正在尝试将两个实例的统计信息合并为一个,以便我可以使用单个 HAProxy 来查看前端/后端统计信息。我试图让两个 hapro
我有一个 Observable,其中每个新值都应该引起一个 HTTP 请求。在客户端,我只关心最新的响应值;但是,我希望每个请求都能完成以进行监控/等。目的。 我目前拥有的是这样的: function
我的网站上有 TinyMCE 插件。在 TinyMCE 插件的 textarea 中添加图像时,我希望这些图像包含延迟加载。我网站的缩略图具有特定类型的延迟加载,其中 src 图像是灰色背景。根据用户
我希望合并润滑间隔,以便如果它们重叠,则从内部第一个时间获取最小值和从内部最后一个时间获取最大值并总结以创建一个跨越整个时间段的新间隔。这是一个reprex: library(lubridate, w
我有一个应用程序,它本质上是一个页眉、主要内容和一个始终可见的页脚。页脚可以改变大小,我想在页脚上方的主内容面板上放置一些工具。主要布局是用 flex 完成的,我阅读文档的理解是绝对定位通过相对于最近
我是一名优秀的程序员,十分优秀!