I want to time a function using an attribute. I would like to do something like this:
[TimeIt]
public MyFunc()
{
//do something
...
return;
}
upon execution of this function, if the time taken by the function is above a threshold, the attribute should log the time using log4net.
This is similar to what the MVC ActionFilterAttribute does, except I don't开发者_如何学JAVA want to use MVC.
Attributes are (with some very few exceptions such as [PrincipalPermission]
which is spotted by the runtime itself) metadata only; so do not cause additional code to magically get invoked. The exception to this is via tools like PostSharp, which at build time locates such attributes and weaves in extra code.
In all other cases you would have to check for this attribute yourself via reflection, and write code to invoke the extra methods from the attributes. This is what ASP.NET MVC does; it identifies an expected family of attributes and calls base-class methods to cause your filters to fire.
If you are writing a plugin framework, this might make sense. If it is for ad-hoc method instrumentation - this isnt going to work without you adding the extra code yourself.
What might be easier is writing an IDisposable
type that writes the elapsed time when it is disposed; then you could do:
using(new MyTimer("My label")) {
//... Your method
}
Perhaps a slight abuse of using
but it should work.
精彩评论