使用C#在asp.net中处理请求所花费的时间

时间:2014-01-23 22:26:09

标签: c# asp.net

我想计算系统在使用C#在asp.net中执行特定操作所花费的时间。当用户点击按钮获得任何结果时,我必须显示结果以及获取结果所花费的时间。任何人都请告诉我必须提供的代码以显示所花费的时间。

2 个答案:

答案 0 :(得分:6)

如果您想测量某个操作需要多长时间,那么您可以使用StopWatch对象。以下用法示例:

class Program
{
    static void Main()
    {
    // Create new stopwatch
    Stopwatch stopwatch = new Stopwatch();

    // Begin timing
    stopwatch.Start();

    // Do something
    for (int i = 0; i < 1000; i++)
    {
        Thread.Sleep(1);
    }

    // Stop timing
    stopwatch.Stop();

    // Write result
    Console.WriteLine("Time elapsed: {0}",
        stopwatch.Elapsed);
    }
}

因此,您需要在场景中执行的操作是在开始执行Action / Method时启动StopWatch,并在返回视图/完成执行之前停止它。然后,您可以使用stopWatch.Elapsed值将其显示给用户。

答案 1 :(得分:0)

原始海报指定了ASP.Net。在ASP.Net中执行此操作的最简单方法可能是在global.asax中注入这样的内容:

private static ILog log = log4net.LogManager.GetLogger( typeof(Global) ) ;

void Application_BeginRequest( object sender , EventArgs e )
{
  Stopwatch timer = new Stopwatch();
  timer.Start();
  Request.RequestContext.HttpContext.Items["timer"] = timer ;
  return ;
}

void Application_EndRequest( object sender , EventArgs e )
{
  Stopwatch timer = (Stopwatch) this.Request.RequestContext.HttpContext.Items["timer"] ;
  timer.Stop() ;
  log.InfoFormat( "HttpVerb={0}, URL={1}, elapsed time={2}" ,
    this.Request.RequestType ,
    this.Request.Url ,
    timer
    ) ;
  return ;
}

如果你想在特定页面的基础上这样做,你需要做类似的事情,分别挂钩Page.PreInit和Page.Unload事件。

你几乎需要使用HttpContext来保持计时器的持续时间:如果你尝试使用静态变量,你就会有你的经典竞争条件。