简体   繁体   English

有没有办法从属性中测量C#函数执行时间?

[英]Is there a way to measure C# function execution time from an attribute?

I'm looking to publish custom performance counters for certain important function calls in the system. 我正在寻找为系统中的某些重要函数调用发布自定义性能计数器。 I'd like to continously monitor these performance counters in a production environment. 我想在生产环境中持续监控这些性能计数器。

Is there a way for me to mark certain functions with a custom attribute that could measure the time it took to execute given function? 有没有办法让我用自定义属性标记某些函数,该属性可以测量执行给定函数所花费的时间? I'd like to avoid injecting custom code and thus polluting business-related functions with monitoring code. 我想避免注入自定义代码,从而用监控代码污染与业务相关的功能。

How can a code from an attribute track the time it took for function to execute? 属性中的代码如何跟踪函数执行所花费的时间?

Please do not suggest use of a Profiler. 请不要建议使用Profiler。 I'm not looking to debug or benchmark performance. 我不打算调试或基准性能。 But simply wanting to track it in on a production 24/7 basis. 但只是想在全天候生产中跟踪它。

Well, you need some code to execute your function and analyze your attribute so it will know that it needs to execute something (eg execution time measurement, in your case) before and after your function - it could be using the Decorator design pattern, Reflection , Proxy object and so on. 好吧,你需要一些代码来执行你的函数并分析你的attribute这样它就会知道它需要在你的函数之前和之后执行某些东西(例如你的情况下执行时间测量) - 它可以使用Decorator设计模式, Reflection代理对象等。

As you tagged, it is an aspect-programming issue and you can take advantage of PostSharp third-party, for example, in order to achieve it. 当您标记时,这是一个方面编程问题,您可以利用PostSharp第三方,例如,为了实现它。

Take a look at this specific page about Performance Counters using PostSharp, it is indeed uses Attributes: http://www.postsharp.net/aspects/examples/performance 使用PostSharp查看有关性能计数器的这个特定页面,它确实使用了属性: http//www.postsharp.net/aspects/examples/performance

To elaborate a little on @pasty's comment, you can intercept your methods invocations with Interception using Unity DI Container , it is indeed requires more code to write, here is a simple sample flow chart of the Unity interception feature: 为了详细说明@ pasty的注释,你可以使用Unity DI Container拦截你的方法调用拦截 ,它确实需要更多代码来编写,这里是Unity拦截功能的简单示例流程图:

显示了此示例中与拦截行为有关的对象

Note to step 3 , where a proxy object is actually returned to the client and thanks to that, the interception behavior is achieved. 请注意步骤3 ,其中代理对象实际返回到客户端,并且由此,实现了拦截行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM