C# 委托 Action 实现代码执行时间日志记录
思路比较简单直接上代码
public void TimeLog(string title, Action action) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); //方法执行 action.Invoke(); stopwatch.Stop(); File.AppendAllLines("D:\\Projects\\ExecutionTimeLog\\Log.txt", new[] { title + " 执行耗时:" + stopwatch.Elapsed.TotalSeconds }); }
调用
int res = 0; TimeLog("Test", () => { res = new Program().Test4(1); res = 3; }); Console.WriteLine(res);