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}");
                });
            });
相关推荐
b***748817 分钟前
前端GraphQL案例
前端·后端·graphql
云飞云共享云桌面18 分钟前
无需配置传统电脑——智能装备工厂10个SolidWorks共享一台工作站
运维·服务器·前端·网络·算法·电脑
福尔摩斯张26 分钟前
《C 语言指针从入门到精通:全面笔记 + 实战习题深度解析》(超详细)
linux·运维·服务器·c语言·开发语言·c++·算法
ganshenml40 分钟前
sed 流编辑器在前端部署中的作用
前端·编辑器
kka杰1 小时前
MYSQL 表的增删查改-更新/删除
数据库·mysql
虚伪的空想家1 小时前
arm架构服务器使用kvm创建虚机报错,romfile “efi-virtio.rom“ is empty
linux·运维·服务器·javascript·arm开发·云原生·kvm
0***K8921 小时前
Vue数据挖掘开发
前端·javascript·vue.js
深藏bIue1 小时前
linux服务器mysql目录下的binlog文件删除
linux·服务器·mysql
q***44811 小时前
mysql配置环境变量——(‘mysql‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件解决办法)
数据库·mysql·adb
蓝胖子的多啦A梦1 小时前
ElementUI表格错位修复技巧
前端·css·vue.js·el-table表格错位