• Stackoverflow 珠玑:C#封装重试指定次数的功能


    最近写的一个 .NET Core 爬虫里用到了需要多次重试的功能,本着无脑输出的精神,google 了一下,还真给我找到了:

        public static T Retry<T, TException>(int timesToRetry, Func<int, T> thingToTry) where TException : Exception {
                // Start at 1 instead of 0 to allow for final attempt
                int i;
                for (i = 1; i < timesToRetry; i++) {
                    try {
                        return thingToTry(i);
                    }
                    catch (TException) {
                        // Maybe: Trace.WriteLine("Failed attempt...");
                    }
                }
    
                return thingToTry(i); // Final attempt, let exception bubble up
            }
    
         //这里我增加了个异步版本 
            public static async Task<T> RetryAsync<T, TException>(int timesToRetry, Func<int, Task<T>> thingToTry) where TException : Exception {
                // Start at 1 instead of 0 to allow for final attempt
                int i;
                for (i = 1; i < timesToRetry; i++) {
                    try {
                        return await thingToTry(i);
                    }
                    catch (TException) {
                        // Maybe: Trace.WriteLine("Failed attempt...");
                    }
                }
    
                return await thingToTry(i); // Final attempt, let exception bubble up
            }
    

    用法就很简单了:

    using static AStaticClass;
    
    class A {
    
        void B() {
            //重试 3 次
            var result = Retry<int, Exception>(3, nTimes => {
                //这里做需要重试的事情
                Console.WriteLine($"第 {nTimes} 次尝试");
                return 99999;
            });
        }
    }
    

    可惜当时看到的时候顺手关了浏览器,找不到原始出处了,等我找回来补上。

  • 相关阅读:
    小程序返回顶部top滚动
    创建对象的几种模式
    前端基础常识
    三行代码让页面中的所有元素增添不同颜色的外边框
    纯css制作小三角
    设计表单
    纯css制作三级菜单
    三栏-中栏流动布局
    三栏固定布局(为栏设定内边距和边框)
    ie8以下不兼容h5新标签的解决方法
  • 原文地址:https://www.cnblogs.com/oldrev/p/7802164.html
Copyright © 2020-2023  润新知