C# Retry库

比如网络访问或硬件参数设置需要重试,可引用gunet上的Polly库。

同步方式(每次重试有不同的时间间隔)

cs 复制代码
            var polly = Policy.Handle<Exception>().WaitAndRetry(new[] { new TimeSpan(0, 0, 1), new TimeSpan(0, 0, 2), new TimeSpan(0, 0, 3) }, (ex, t, retryCnt, context) => {
                Debug.WriteLine($"{ex.Message}, {t}, {retryCnt}");
            });
            polly.ExecuteAndCapture(() => {
                Thread.Sleep(1000);
                var random = new Random();
                var v = random.Next(0, 10);
                if (v < 50)
                    throw new Exception("V < 50");
                Debug.WriteLine($"polly.ExecuteAndCapture {Thread.CurrentThread.ManagedThreadId}");
            });

异步方式(每次重试有不同的时间间隔)

cs 复制代码
            var polly = Policy.Handle<Exception>().WaitAndRetryAsync(new[] { new TimeSpan(0, 0, 1), new TimeSpan(0, 0, 5), new TimeSpan(0, 0, 10) }, (ex, t, retryCnt, context) => {
                Debug.WriteLine($"{ex.Message}, {t}, {retryCnt}  ThreadID={Thread.CurrentThread.ManagedThreadId}");
            });
            polly.ExecuteAndCaptureAsync(async () => {
                await Task.Run(() => {
                    Thread.Sleep(1000);
                    var random = new Random();
                    var v = random.Next(0, 10);
                    if (v < 50)
                        throw new Exception("V < 50");
                    Debug.WriteLine($"polly.ExecuteAndCapture {Thread.CurrentThread.ManagedThreadId}");
                });
            });
相关推荐
leobertlan2 小时前
2025年终总结
前端·后端·程序员
子兮曰3 小时前
OpenClaw架构揭秘:178k stars的个人AI助手如何用Gateway模式统一控制12+通讯频道
前端·javascript·github
invicinble3 小时前
对linux形成认识
linux·运维·服务器
马克Markorg3 小时前
常见的向量数据库和具有向量数据库能力的数据库
数据库
技术路上的探险家3 小时前
8 卡 V100 服务器:基于 vLLM 的 Qwen 大模型高效部署实战
运维·服务器·语言模型
百锦再3 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
莲华君3 小时前
React快速上手:从零到项目实战
前端·reactjs教程
百锦再3 小时前
React编程高级主题:测试代码
android·前端·javascript·react.js·前端框架·reactjs
半桔3 小时前
【IO多路转接】高并发服务器实战:Reactor 框架与 Epoll 机制的封装与设计逻辑
linux·运维·服务器·c++·io
绵绵细雨中的乡音3 小时前
深入理解 ET 与 LT 模式及其在 Reactor 模型中的应用
服务器·网络·php