将数据写入 Web 服务器时,我的测试显示 HttpWebRequest.ReadWriteTimeout 被忽略,这与MSDN规范。例如,如果我将 ReadWriteTimeout 设置为 1(= 1 毫秒),调用 myRequestStream.Write() 并传入需要 10 秒传输的缓冲区,则使用 .NET 3.5 SP1 会成功传输并且永远不会超时。在 Mono 2.6 上运行的相同测试按预期立即超时。可能出什么问题了?
似乎存在一个错误,即在由 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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)