在.NET中忽略了HttpWebRequest ReadWriteTimeout;在Mono工作

时间:2010-04-20 22:38:05

标签: httpwebrequest timeout

将数据写入Web服务器时,我的测试显示HttpWebRequest.ReadWriteTimeout被忽略,与MSDN spec相反。例如,如果我将ReadWriteTimeout设置为1(= 1毫秒),则调用myRequestStream.Write()传入一个需要10秒钟传输的缓冲区,它会成功传输,并且永远不会超时使用.NET 3.5 SP1。在Mono 2.6上运行的相同测试按预期立即超时。可能有什么不对?

1 个答案:

答案 0 :(得分:4)

似乎存在一个错误,即在BeginGetRequestStream()返回给您的Stream实例上设置的写入超时不会传播到本机套接字。我将提交一个错误,以确保在将来的.NET Framework版本中更正此问题。

这是一种解决方法。

private static void SetRequestStreamWriteTimeout(Stream requestStream, int timeout)
{
  // Work around a framework bug where the request stream write timeout doesn't make it
  // to the socket. The "m_Chunked" field indicates we are performing chunked reads. Since
  // this stream is being used for writes, the value of this field is irrelevant except
  // that setting it to true causes the Eof property on the ConnectStream object to evaluate
  // to false. The code responsible for setting the socket option short-circuits when it
  // sees Eof is true, and does not set the flag. If Eof is false, the write timeout
  // propagates to the native socket correctly.

  if (!s_requestStreamWriteTimeoutWorkaroundFailed)
  {
    try
    {
      Type connectStreamType = requestStream.GetType();
      FieldInfo fieldInfo = connectStreamType.GetField("m_Chunked", BindingFlags.NonPublic | BindingFlags.Instance);
      fieldInfo.SetValue(requestStream, true);
    }
    catch (Exception)
    {
      s_requestStreamWriteTimeoutWorkaroundFailed = true;
    }
  }

  requestStream.WriteTimeout = timeout;
}

private static bool s_requestStreamWriteTimeoutWorkaroundFailed;