Rx中如何打印Retry(5)的重试次数?无法找到.Dump扩展方法
解决Rx框架重试信息打印问题
关于.Dump()方法
.Dump()是LINQPad专属的扩展方法,用于快速输出结果到LINQPad控制台,普通C#项目中没有这个方法,你可以用Console.WriteLine()替代实现打印功能。
实现重试计数打印
默认的Retry(5)无法获取重试次数,要实现打印“Retry #1”这类信息,需要改用RetryWhen操作符手动跟踪重试次数:
修改后的完整代码如下:
using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; var test = new Test(new HttpClient()); var result = await test.GetAsync(); Console.WriteLine($"Result: {result}"); public sealed class Test { private readonly HttpClient _httpClient; public Test(HttpClient httpClient) { _httpClient = httpClient; } public Task<string> GetAsync() { int retryCount = 0; const int maxRetries = 5; return Observable .FromAsync(() => _httpClient.GetAsync("http://www.mocky.io/v2/5e307edf3200005d00858b49")) .SubscribeOn(TaskPoolScheduler.Default) // 替换Retry为RetryWhen,实现带计数的重试 .RetryWhen(errors => errors .Take(maxRetries) .Do(_ => { retryCount++; Console.WriteLine($"Retry #{retryCount}"); }) // 可选:每次重试前延迟1秒,避免频繁请求 .Delay(TimeSpan.FromSeconds(1))) .Timeout(TimeSpan.FromSeconds(5)) .Do(x => Console.WriteLine($"Is message successful? {x.IsSuccessStatusCode}")) .SelectMany(async x => { var response = await x.Content.ReadAsStringAsync(); return response; }) .Catch<string, TimeoutException>(_ => Observable.Return("Timeout")) .Catch<string, Exception>(ex => Observable.Return(ex.Message)) .ToTask(); } }
代码说明
- 用
RetryWhen替代Retry,通过错误流捕获每次失败,在Do操作中递增重试计数并打印信息 Take(maxRetries)限制最大重试次数,和原Retry(5)效果一致- 可选的
Delay操作让重试间隔一段时间,降低服务请求压力
内容的提问来源于stack exchange,提问作者nop
相关产品推荐
相关产品推荐

