如何编写通用代码以获取c#中方法执行所花费的时间

Imr*_*zvi 0 c#

我需要记录各种方法所花费的时间,我的企业服务器应用程序中的代码块我现在使用的是秒表,示例代码我实现的如下:

var sw = new Stopwatch();
sw.Start();
DoSomething();
sw.Stop();
logManager.LogInformation(String.Format("Time taken by DoSomething function is {0} ms.", sw.ElapsedMilliseconds));
Run Code Online (Sandbox Code Playgroud)

我在许多.cs文件的许多地方写这样的文字,我只是想通过编写一种常用的方法或扩展来减少这种手工工作来测量所用的时间.为此,我想用时间测量方法包裹我的实际方法,如:

long elapsedMilliseconds = ExecuteAndGetTimeTaken(this.DoSomething());
Run Code Online (Sandbox Code Playgroud)

或类似的通用扩展方法

long elapsedMilliseconds = this.DoSomething().GetTimeTaken();
Run Code Online (Sandbox Code Playgroud)

如果方法记录消息的时间也很好,例如

long elapsedMilliseconds = ExecuteAndGetTimeTaken(this.DoSomething(),logManager,message);
Run Code Online (Sandbox Code Playgroud)

如何编写通用类/方法或扩展来解决目的?

CSh*_*pie 6

这应该做:

void ExecuteAndMeasureTimeTaken(Action action, string message)
{
    if(action == null) throw new ArgumentNullException();
    else
    {
        var sw = new Stopwatch();
        sw.Start();

        action();

        sw.Stop(); 

        LogMessage(message , sw.ElapsedMilliseconds);
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

logManager.ExecuteAndMeasureTimeTaken(() => GC.Collect(), "Time taken by GC after each Listning is {0} ms.");
Run Code Online (Sandbox Code Playgroud)

它真的需要一个LogManager参数吗?

如果是这样,您可以将其添加到LogManager本身.