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}");
                });
            });
相关推荐
安全系统学习5 分钟前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss
涛哥码咖21 分钟前
chrome安装AXURE插件后无效
前端·chrome·axure
焱焱枫26 分钟前
Oracle获取执行计划之10046 技术详解
数据库·oracle
OEC小胖胖33 分钟前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
(:满天星:)1 小时前
第31篇:块设备与字符设备管理深度解析(基于OpenEuler 24.03)
linux·运维·服务器·网络·centos
小陶来咯1 小时前
【仿muduo库实现并发服务器】Acceptor模块
运维·服务器
行云&流水1 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
爱莉希雅&&&1 小时前
shell编程之awk命令详解
linux·服务器·git
笑稀了的野生俊1 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Sally璐璐1 小时前
零基础学HTML和CSS:网页设计入门
前端·css