【发布时间】:2018-09-19 09:24:28
【问题描述】:
我有兴趣测量执行特定方法所需的时间。
我认为使用自定义属性而不是乱扔代码来启动/停止秒表并发送到记录器会非常方便。如果我可以使用属性来装饰有问题的方法,那将非常方便!
我能够在这篇文章之后创建自定义属性: https://docs.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes
像这样:
public class MonitorExecutionTime : Attribute
{
private Stopwatch measureExecution;
// Start measuring on instantiation
public MonitorExecutionTime()
{
measureExecution = new Stopwatch();
measureExecution.Start();
}
// how do I hook into end invoke?
public MethodHasEnded()
{
measureExecution.Stop();
TimeSpan timeSpan = measureExecution.Elapsed;
Console.WriteLine("Time: {0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
}
}
但我不确定如何“捕获”正在调用和结束调用执行点,以便启动秒表和停止秒表(测量时间并记录它)。
有没有人在 .net 核心应用程序中采用这种方法?提前感谢您的任何指点!
【问题讨论】:
-
我不确定,但你检查过你的属性类的析构函数是什么时候执行的吗?可以将其用作您的方法结束挂钩吗?
标签: logging .net-core azure-application-insights custom-attributes stopwatch