如何在WebResponse上获得第一位的时间?

时间:2012-06-09 21:11:08

标签: c# .net httpwebrequest httpwebresponse

使用C#,我需要确定从WebRequest开始接收响应所需的时间(现在,我并不担心下载完整响应所需的时间)。

据我所知,要做到这一点,我需要使用WebRequest的异步方法。以下是我的想法:

public TimeSpan TimeToFirstBit(string url)
{
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  request.Accept = "*/*";

  DateTime? firstBit = null;
  DateTime start = DateTime.Now;

  IAsyncResult asyncResult = request.BeginGetResponse(
      (async) => { firstBit = DateTime.Now; },
      null);

  asyncResult.AsyncWaitHandle.WaitOne();
  request.EndGetResponse(asyncResult);

  TimeSpan result = start - firstBit.Value; 
  // Previous line generates a System.InvalidOperationException: 
  // "Nullable object must have a value."

  return result;

}

这会导致“Nullable对象必须有值”。这似乎表明WaitOne()和EndGetResponse方法实际上并没有等待异步调用完成,正如我认为的那样。

那么我该如何等待BeginGetResponse()完成?这确实是确定请求响应时间的正确方法吗?

1 个答案:

答案 0 :(得分:4)

如果您只想了解线路上请求和响应之间的延迟,请使用Fiddler等网络数据包嗅探器。我对数据包级别工具的时序数据比对进程内定时器更有信心。通过包含.net堆栈开销,进程内测量可能略有偏差。如果您想知道服务器响应的速度,您不希望包含客户端开销。