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 { ////// /// ////// /// /// /// /// /// public static void Excute (Action action, T1 arg1, string customerName, string actionName, string poNumber, int retryCount = 3) { Excute (action, arg1, customerName, actionName, poNumber, new TimeSpan(0, 0, 3)); } /// /// 重试一个参数带返回值 /// ///参数类型1 ///返回类型 /// 执行的方法 /// 参数1 /// 重试间隔 /// 重试次数 ///返回类型T public static void Excute(Action action, T1 arg1,string customerName,string actionName, string poNumber, TimeSpan retryInterval, int retryCount = 3) { //var exceptions = new List (); 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); } } } }}
在其他类中调用
ActionExecutor.Excute(RequesetOrder, order, CUSTOMER_NAME, "request order detail", order.OrderNumber);//RequesetOrder 类方法//order 是RequesetOrder的参数
posted on 2017-04-18 17:46 阅读( ...) 评论( ...)