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}");
                });
            });
相关推荐
lichenyang45310 小时前
Docker 学习笔记(一):为什么需要镜像、容器和仓库?
前端
kyriewen10 小时前
别再对着 TypeScript 报错发呆了:我把 10 个最常见的红色波浪线翻译成了人话
前端·javascript·typescript
IT_陈寒10 小时前
SpringBoot自动配置的坑,我的API突然就404了
前端·人工智能·后端
GBASE11 小时前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
奇奇怪怪的11 小时前
Embedding 模型 10+ 横向评测
前端
陈广亮11 小时前
Monorepo 从 0 到 1 实操指南 2026 版:pnpm catalogs + Turborepo 2.x + changesets 全链路
前端
子兮曰11 小时前
OpenMontage 深度解剖:你的 AI 编程助手,其实是个视频工作室
前端·后端·ai编程
敲代码的鱼11 小时前
PDF 预览与签名批注写回 支持安卓 iOS 鸿蒙 UTS插件
android·前端·ios
子兮曰11 小时前
前端工具链的「Rust 化」:一场没有赢家的军备竞赛?
前端·后端·rust