zoukankan      html  css  js  c++  java
  • C# 实现retry

    C# 有try-catch ,但是没有retry 功能,通过用有限次循环的办法来模拟Retry,当然中间需要加一个等待的过程。

    我们可以利用C#的匿名方法(anonymous methods)匿名委托(anonymous delegate)修饰此功能

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace Exchange.Common
    {
        public class ActionExecutor
        {
            /// <summary>
            /// 
            /// </summary>
            /// <typeparam name="T1"></typeparam>
            /// <param name="action"></param>
            /// <param name="arg1"></param>
            /// <param name="customerName"></param>
            /// <param name="actionName"></param>
            /// <param name="poNumber"></param>
            /// <param name="retryCount"></param>
            public static void Excute<T1>(Action<T1> action, T1 arg1, string customerName, string actionName, string poNumber, int retryCount = 3)
            {
                Excute<T1>(action, arg1, customerName, actionName, poNumber, new TimeSpan(0, 0, 3));
            }
            /// <summary>
            /// 重试一个参数带返回值
            /// </summary>
            /// <typeparam name="T1">参数类型1</typeparam>
            /// <typeparam name="T">返回类型</typeparam>
            /// <param name="func">执行的方法</param>
            /// <param name="arg1">参数1</param>
            /// <param name="retryInterval">重试间隔</param>
            /// <param name="retryCount">重试次数</param>
            /// <returns>返回类型T</returns>
            public static void Excute<T1>(Action<T1> action, T1 arg1,string  customerName,string actionName, string poNumber, TimeSpan retryInterval, int retryCount = 3)
            {
                //var exceptions = new List<Exception>();
    
                for (int retry = 0; retry < retryCount; retry++)
                {
                    try
                    {
                        action(arg1);
                        return;
                    }
                    catch (Exception ex)
                    {
                        ExceptionHandler.Do(string.Format("{0} {1} "{2}"  error", customerName, actionName, poNumber, retry), ex);
                        //exceptions.Add(ex);
                        Thread.Sleep(retryInterval);
                    }
                }
            }
        }
    }
    View Code

    在其他类中调用

    ActionExecutor.Excute(RequesetOrder, order,
                                            CUSTOMER_NAME,
                                                    "request order detail", order.OrderNumber);
    
    //RequesetOrder 类方法
    //order 是RequesetOrder的参数
  • 相关阅读:
    ie的bug及兼容性
    解决多次include后全局变量global失效的问题
    针对MYISAM表锁的解决方案(转)
    解决二进制文件冲突
    linux基本命令(1) 开关机操作
    子网掩码(NETMASK),ip地址,默认网关
    linux中常见设备对照表
    解决base64通过http传输后+变空格的问题
    mysql 查询某值是否存在于某结果集或表中
    laravel 报错 No query results for model
  • 原文地址:https://www.cnblogs.com/sxypeace/p/6729076.html
Copyright © 2011-2022 走看看