0

我正在尝试包装一堆与 API 服务器交互的方法,以测试每个方法需要多长时间。

例如我想包装这些方法:

    public DCResultOfValidateSiteForUser ValidateSiteForUser(int UserId, int UserType, int SiteId)
    {
        return Service.ValidateSiteForUser(UserId, UserType, SiteId);
    }
    public DCResultOfIsSystemInStandby IsSystemInStandby()
    {
        return Service.IsSystemInStandby();
    }

这是我想围绕上述方法的内容:

    public static T TestPerf<T>(Action action)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        action();

        sw.Stop();

        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase methodBase = stackFrame.GetMethod();

        TextWriter tw = new StreamWriter("perfLog.txt", true);
        string s = String.Format("{0} {1}{2,15}", String.Format("{0:M/d/yyyy HH:mm:ss}", DateTime.Now), methodBase.Name, sw.Elapsed);
        tw.WriteLine(s);
        tw.Close();

        return default(T);
    }

但是,由于 Action 返回 void。然后我做了:

    public DCResultOfValidateSiteForUser ValidateSiteForUser(int UserId, int UserType, int SiteId)
    {
        TestPerf<DCResultOfValidateSiteForUser>(() => Service.ValidateSiteForUser(UserId, UserType, SiteId));
        return Service.ValidateSiteForUser(UserId, UserType, SiteId);
    }
    public DCResultOfIsSystemInStandby IsSystemInStandby()
    {
        TestPerf<DCResultOfIsSystemInStandby>(() => Service.IsSystemInStandby());
        return Service.IsSystemInStandby();
    }

我想要的是:

    public DCResultOfIsSystemInStandby IsSystemInStandby()
    {
        return TestPerf<DCResultOfIsSystemInStandby>(() => Service.IsSystemInStandby());
    }

我不想将秒表代码放入每个方法中,因为有 100 个。

我感谢可以提供的任何帮助。

谢谢

4

1 回答 1

1

这应该编译而不是执行两次方法:

public DCResultOfValidateSiteForUser ValidateSiteForUser(int UserId, int UserType, int SiteId)
{
    DCResultOfValidateSiteForUser result = null;
    TestPerf<DCResultOfValidateSiteForUser>(() => result = Service.ValidateSiteForUser(UserId, UserType, SiteId));
    return result;
}
于 2012-09-28T19:15:13.123 回答