使用属性启动函数

时间:2015-07-08 05:29:13

标签: c# attributes stopwatch

我有一个使用秒表实例的功能,并测量放入任何方法的时间。现在,我必须为每种方法开始和停止。我想现在这样使用属性。我想在每个自动启动和停止测量时间的函数的方法上放置一个属性。

功能代码:

 [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 个答案:

答案 0 :(得分:0)

这可能不适用于.NET Framework。 Aspect oriented programming由各种第三方提供商实施,Postsharp可能是最常用的提供商。

您可以实现自己的属性,但如果没有AOP框架,它们将不会为您执行任何代码。它们只是您可以使用反射查询的元数据。

答案 1 :(得分:0)

解决这个问题的另一种方法是:

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

因此,如果您正在进行一些优化并希望测试运行时,您可以基本上将方法委派给此函数并获取输出。

问题太宽泛了