日期:2014-05-18  浏览次数:20519 次

[100分],请高手看看,以下的Application是不是用的有毛病,初学,明白了立即给分。
在网上看到以下测试页面执行时间的代码

在Global.asax.cs文件中

protected   void   Application_BeginRequest(Object   sender,   EventArgs   e)
{
          Application[ "StartTime "]   =   System.DateTime.Now;
}
protected   void   Application_EndRequest(Object   sender,   EventArgs   e)
{
          System.DateTime   startTime   =   (System.DateTime)Application[ "StartTime "];
          System.DateTime   endTime   =   System.DateTime.Now;
          System.TimeSpan   ts   =   endTime   -   startTime;
          Response.Write( "页面执行时间: "+   ts.Milliseconds   + "   毫秒 ");
        }
 

但我觉得有问题,比如:第一个用户访问页面时,Application_BeginRequest被触发了,可是这时,又来了第个用户访问页面又触发Application_BeginRequest{注意:第一个用户还没有触发Application_EndRequest呢},这样一来是不是测试结果就失去准确度了呢。

由于本人初学,请问如何在这种情况下保证测试结果的准确[即在第一个用户执行Application_EndRequest之前,不让其它用户执行Application_BeginRequest]。


请不要说是Application.Lock()^_^

明白一定结贴。

------解决方案--------------------
你的猜测是的,误用了 Appliction 对象,此对象对任意请求访问的值是一样的

应该用 Session
------解决方案--------------------
跟Jinglecat指出的一样,这样的测量应该用跟当前用户有关的变量,即应该用Session,但其实你要测试的是当前请求,那么应该用HttpContext.Current.Items


HttpContext.Current.Items[ "StartTime "] = System.DateTime.Now;

System.DateTime startTime = (System.DateTime)HttpContext.Current.Items[ "StartTime "];

但注意,System.DateTime也许精度不够,那样使用System.Diagnostics.Stopwatch

protected void Application_BeginRequest(object sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
HttpContext.Current.Items[ "StartTime "] = sw;
}


protected void Application_EndRequest(object sender, EventArgs e)
{

Stopwatch sw = (Stopwatch)HttpContext.Current.Items[ "StartTime "];
sw.Stop();
HttpContext.Current.Response.Write(sw.ElapsedMilliseconds);
}

或者QueryPerformanceCounter() 和 QueryPerformanceFrequency(),参考

http://www.codeproject.com/csharp/highperformancetimercshar.asp

------解决方案--------------------
应该用session
application是全局的,可以实现所有用户共享,而session是会话级的,每个用户对应一个;
对于用户独自的信息用Session,而对于整个网站共享信息用Applicatino
------解决方案--------------------
hehe,是应该用Session的
------解决方案--------------------
应该用session
application是全局的,可以实现所有用户共享,而session是会话级的,每个用户对应一个;
对于用户独自的信息用Session,而对于整个网站共享信息用application