1

I have a function that uses a stopwatch instance and measure time of any method put inside. now, I have to start and stop that for every method. I want to so this now using attribute. I want to place just an attribute over every method which automatically starts and stops my function which measures the time.

The code of function:

 [DataContract]
[Serializable]

public class AppTrace:BaseModel<AppTrace>
{
    [DataMember]
    public string Comment;
    [DataMember]
    public string MethodName;
    [DataMember]
    public DateTime StartTimeStamp;
    [DataMember]
    public int Duration;
    [DataMember]
    public int UserObjectId;
    [DataMember]
    public string MachineName;
    [DataMember]
    public int ToolId;
    private System.Diagnostics.Stopwatch stpWatch;

public AppTrace(string comment,string methodName,int userObjectId ,string machineName = "",int? toolId=null)

    {
        MethodName = methodName;
        UserObjectId = userObjectId;
        StartTimeStamp = DateTime.UtcNow;
        Comment = comment;
        MachineName = machineName;

        stpWatch = new System.Diagnostics.Stopwatch();
        stpWatch.Start();
    }

    public AppTrace()
    {
    }

    public void CloseTrace()
    {
        this.stpWatch.Stop();
        Duration=Convert.ToInt32( this.stpWatch.ElapsedMilliseconds);
    }

2 Answers2

0

That probably won't work with only the .NET Framework. Aspect oriented programming is implemented by various third party providers, Postsharp probably being the most used.

You can implement your own attributes, but without an AOP framework, they will not execute any code for you. They are just metadata that you can query with reflection.

Community
  • 1
  • 1
nvoigt
  • 75,013
  • 26
  • 93
  • 142
0

Another way to solve this, would be something like :

protected void StopwatchThis(Action func)
        {
            //some code
            func.Invoke();
            //more code
        }

So if you are doing some optimization and want to test the run time, you could basicly just delegate your methods to this function and get the output.

question bit too broad

evictednoise
  • 587
  • 1
  • 7
  • 19