监控任务执行时长(Task)并审计

2020年10月10日 2901点热度 1人点赞 0条评论
内容目录

编写一个拓展:

    public static class TaskExtensions
    {
        public static Task Start(this Task task, out Stopwatch stopwatch)
        {
            stopwatch = new Stopwatch();
            stopwatch.Start();
            return task;
        }

        public static Task<T> Start<T>(this Task<T> task, out Stopwatch stopwatch)
        {
            stopwatch = new Stopwatch();
            stopwatch.Start();
            return task;
        }

        public static Task<T> End<T>(this Task<T> task, MethodBase method, int time, Stopwatch stopwatch)
        {
            return End(task, method, time, stopwatch);
        }

        public static Task End(this Task task, MethodBase method, int time, Stopwatch stopwatch)
        {
            return End(task, method, time, stopwatch);
        }

        private static T End<T>(T task, MethodBase method, int time, Stopwatch stopwatch) where T : Task
        {
            task.ContinueWith(x =>
            {
                stopwatch.Stop();
                var thisTime = stopwatch.ElapsedMilliseconds;
                if (thisTime > time)
                {
                    MyTask(method.DeclaringType.DeclaringType, (MethodInfo)method, thisTime);
                }

            });
            return task;
        }

        /// <summary>
        /// 加上审计记录,执行此任务的函数位置等
        /// </summary>
        /// <param name="type"></param>
        /// <param name="info"></param>
        /// <param name="time"></param>
        private static void MyTask(Type type, MethodInfo info, long time)
        {
            Console.WriteLine($"执行位置 {type.Name}-{info.DeclaringType.FullName},耗时 {time} ms");
        }
}

使用方法:

            static async Task Main(string[] args)
            {
                var method = MethodBase.GetCurrentMethod();
                for (int i = 0; i < 10; i++)
                {
                    var task = await T()
                        .Start(out var watch)
                        .End(method, 1000, watch);
                    Console.WriteLine($"第 {i} 次执行");
                }
            }

            /// <summary>
            /// 被执行的任务
            /// </summary>
            /// <returns></returns>
            private static async Task<string> T()
            {
                await Task.Delay(new Random().Next(980, 1001));
                return "aaaa";
            }

这样可以记录每个任务执行的时间,并且记录执行位置,方便对性能进行分析和定位异常位置。

痴者工良

高级程序员劝退师

文章评论