本文介绍了NET中忽略了HttpWebRequest ReadWriteTimeout;在Mono中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When writing data to a web server, my tests show HttpWebRequest.ReadWriteTimeout is ignored, contrary to the MSDN spec. For example if I set ReadWriteTimeout to 1 (=1 msec), call myRequestStream.Write() passing in a buffer that takes 10 seconds to transfer, it transfers successfully and never times out using .NET 3.5 SP1. The same test running on Mono 2.6 times out immediately as expected. What could be wrong?

推荐答案

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

There appears to be a bug where the write timeout, when set on the Stream instance returned to you by BeginGetRequestStream(), is not propagated down to the native socket. I will be filing a bug to make sure this issue is corrected for a future release of the .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中忽略了HttpWebRequest ReadWriteTimeout;在Mono中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:00
查看更多