Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Time a function using attribute

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 want to use MVC.

like image 279
nsdiv Avatar asked Dec 18 '10 18:12

nsdiv


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


1 Answers

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.

like image 98
Marc Gravell Avatar answered Sep 22 '22 14:09

Marc Gravell