zoukankan      html  css  js  c++  java
  • 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;
            });
        }
    }
    

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

  • 相关阅读:
    转:验证日期的正则表达式比较全面地验证
    IIS应用地址池监控
    Net预编译 真的好用与否
    关键字检索,找到所有数据
    vue 文件上传自定义实现
    docker 基础(一)
    input表单中嵌入百度地图
    linux系统光盘开机自动挂载-配置本地yum源
    linux学习笔记基础篇(一)
    构建apache web 服务器
  • 原文地址:https://www.cnblogs.com/oldrev/p/7802164.html
Copyright © 2011-2022 走看看