/// <summary> /// 方法帮助类 /// </summary> public class ActionHelper { /// <summary> /// 执行时间阀值 /// </summary> public static readonly uint ElapsedMillisecondsLimit = 100; /// <summary> /// 统一计算执行时间 /// </summary> /// <param name="action">执行方法</param> /// <returns></returns> public static uint ComputeActionCostMilliseconds(Action action) { var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); // 开始监视 action(); stopwatch.Stop(); // 停止监视 var timeSpan = stopwatch.Elapsed; // 获取总时间 return (uint)timeSpan.TotalMilliseconds; } /// <summary> /// 统一计算执行时间 /// </summary> /// <param name="action">执行方法</param> /// <returns>Result.Data为执行结果。Result.Message为所消费的毫秒数</returns> public static ActionElapseResult<T> ComputeFuctionCostMilliseconds<T>(Func<T> action) { var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); // 开始监视 var obj = action(); stopwatch.Stop(); // 停止监视 var timeSpan = stopwatch.Elapsed; // 获取总时间 return new ActionElapseResult<T>() { Data = obj, ElapsedMilliseconds = (uint)(timeSpan.TotalMilliseconds) }; } /// <summary> /// 统一计算执行时间并记录日志 /// </summary> /// <param name="action">执行方法</param> /// <param name="elapsedMillisecondsLimit">执行所消费的时间阀值(超过阀值则记录日志)</param> /// <param name="loggerAction">日志执行方法</param> /// <returns>Result.Data为执行结果。Result.Message为所消费的毫秒数</returns> public static T ComputeFuctionCostMilliseconds<T>(Func<T> action, uint elapsedMillisecondsLimit, Action<uint> loggerAction) { return ComputeFuctionCostMilliseconds(action, (ms) => (elapsedMillisecondsLimit == 0 || ms > elapsedMillisecondsLimit), loggerAction); } /// <summary> /// 统一计算执行时间并记录日志 /// </summary> /// <param name="action">执行方法</param> /// <param name="elapsedMillisecondsLimit">是否根据消费时间判断需要记录日志</param> /// <param name="loggerAction">日志执行方法</param> /// <returns>Result.Data为执行结果。Result.Message为所消费的毫秒数</returns> public static T ComputeFuctionCostMilliseconds<T>(Func<T> action, Func<uint,bool> elapsedMillisecondsLimit, Action<uint> loggerAction) { var result = ComputeFuctionCostMilliseconds(action); var ms = (uint)(result.ElapsedMilliseconds); if (loggerAction != null && elapsedMillisecondsLimit(ms)) { loggerAction(ms); } return result.Data; } }