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

3

当向Web服务器写入数据时,我的测试表明HttpWebRequest.ReadWriteTimeout被忽略,与 MSDN规范相反。例如,如果我将ReadWriteTimeout设置为1(= 1毫秒),调用myRequestStream.Write()传入需要10秒钟才能传输的缓冲区,则使用.NET 3.5 SP1成功传输并且从未超时。在Mono 2.6上运行的相同测试立即超时,如预期。可能出了什么问题?


你的.NET和mono测试是否针对同一台服务器,并且来自同一主机? - feroze
1个回答

4

看起来有一个错误,在通过BeginGetRequestStream()返回给您的流实例上设置写超时时,它并没有向本地套接字传播。我将提交一个错误报告,确保在 .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;

非常感谢!我会尝试这个解决方法。看起来即使在 .NET 框架修复后,这个修复也是兼容的? - jimvfr
测试了解决方法,它运行良好。你能告诉我这个 Microsoft bug 的编号吗? - jimvfr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接