为什么HttpWebRequest.BeginGetResponse()同步完成?

Ram*_*ich 5 .net c# asp.net performance c#-4.0

我正在高负载下测试ASP.NET(.NET 4)Web应用程序,并发现在某些条件下HttpWebRequest.BeginGetResponse()同步完成不抛出任何异常.

在高负载下运行多个ASP.NET线程中的以下代码后,我发现"WEBR​​EQUEST COMPLETED SYNC!" 日志中的消息.

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
var result = webRequest.BeginGetResponse(internalCallback, userState);
if (result.CompletedSynchronously)
{
    Trace.Error("WEBREQUEST COMPLETED SYNC!");
}
Run Code Online (Sandbox Code Playgroud)

注意:

  1. 如果达到线程池容量,则抛出InvalidOperationException
  2. 如果在连接期间发生错误,则抛出相应的异常

在我的情况下,没有例外!

我已经反编译了System.Net程序集,发现在某些情况下它确实是可能的.但我不明白这些条件是什么意思(System.Net.Connection.SubmitRequest(HttpWebRequest request, bool forcedsubmit)):

if (this.m_Free && this.m_WriteDone && !forcedsubmit && (this.m_WriteList.Count == 0 || request.Pipelined && !request.HasEntityBody && (this.m_CanPipeline && this.m_Pipelining) && !this.m_IsPipelinePaused))
{
  this.m_Free = false;
  needReConnect = this.StartRequest(request, true);
  if (needReConnect == TriState.Unspecified)
  {
    flag = true;
    this.PrepareCloseConnectionSocket(ref returnResult);
    this.Close(0);
  }
}
Run Code Online (Sandbox Code Playgroud)

何时以及为何可以这样做?

Par*_*rma 4

find this for CompletedSynchronouslypropperty
使用此属性来确定异步操作是否同步完成。例如,如果 I/O 请求很小,则此属性可以针对异步 I/O 操作返回 true。
这里

编辑:-我怀疑响应可能会被缓存。因此尝试通过使用来停止缓存响应request.CachePolicy = new HttpRequestCachePolicy(/*caching type*/);