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