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}");
                });
            });
相关推荐
佛系打工仔2 小时前
绘制K线第二章:背景网格绘制
android·前端·架构
Java.熵减码农3 小时前
解决Linux修改环境变量后导致登录循环进不去系统的问题
linux·运维·服务器
计算机毕设VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue医院设备管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
明天好,会的3 小时前
分形生成实验(五):人机协同破局--30万token揭示Actix-web状态管理的微妙边界
运维·服务器·前端
Mr__Miss3 小时前
保持redis和数据库一致性(双写一致性)
数据库·redis·spring
C_心欲无痕4 小时前
nginx - alias 和 root 的区别详解
运维·前端·nginx
Knight_AL4 小时前
Spring 事务传播行为 + 事务失效原因 + 传播行为为什么不用其他模式
数据库·sql·spring
倔强的石头_5 小时前
时序数据时代的“存储与分析困局”解析及金仓解决方案
数据库
计算机毕设VX:Fegn08955 小时前
计算机毕业设计|基于springboot + vue小型房屋租赁系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计