我正在尝试包装一系列与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个。
感谢您提供的任何帮助。
由于
答案 0 :(得分:1)
这应该编译而不是两次执行方法:
public DCResultOfValidateSiteForUser ValidateSiteForUser(int UserId, int UserType, int SiteId)
{
DCResultOfValidateSiteForUser result = null;
TestPerf<DCResultOfValidateSiteForUser>(() => result = Service.ValidateSiteForUser(UserId, UserType, SiteId));
return result;
}