【发布时间】:2010-10-28 07:02:59
【问题描述】:
我有以下代码,在调用它约 60 次(20 个并发连接)后,它开始超时。如果我将超时时间从 10 分钟降低到 1 分钟,它们会在 ~34 次下载时开始超时。是什么赋予了?我知道如果你没有正确关闭你的回复,你会得到这个,但我肯定会关闭它:
//===============================================================================
/// <summary>
/// Executes the request and returns the response as a byte array. Useful if the
/// response should return a file.
/// </summary>
private static byte[] GetResponse(HttpWebRequest webRequest)
{
//---- declare vars
HttpWebResponse response = null;
List<byte> buffer = new List<byte>();
int readByte;
//---- try to get the response, always wrap it.
try
{ response = webRequest.GetResponse() as HttpWebResponse; }
//---- catch all
catch (Exception e)
{
if (response != null) { response.Close(); }
throw new ConnectionFailedException("Failed to get a response", e);
}
try
{
//---- if the response is ok
if (response.StatusCode == HttpStatusCode.OK)
{
//---- get the response stream
using (Stream stream = response.GetResponseStream())
{
//---- read each byte, one by one into the byte buffer
while ((readByte = stream.ReadByte()) > -1)
{
buffer.Add((byte)readByte);
}
//---- close the stream
stream.Close();
response.Close();
}
//---- return the buffer as a byte array
return buffer.ToArray();
}
//---- if the request wasn't auth'd
else if (response.StatusCode == HttpStatusCode.Forbidden || response.StatusCode == HttpStatusCode.Unauthorized)
{
if (response != null) { response.Close(); }
throw new AuthenticationFailedException(response.StatusDescription);
}
//---- any other errors
else
{
if (response != null) { response.Close(); }
throw new ConnectionFailedException(response.StatusDescription);
}
}
finally { if (response != null) { response.Close(); } }
}
//===============================================================================
想法?
另外,我在创建它时将 TimeOut 和 ReadWriteTimeout 都设置为 10 分钟:
//---- 创建网络请求 HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
//---- 设置 10 分钟超时 webRequest.Timeout = 600000; webRequest.ReadWriteTimeout = 600000;
【问题讨论】:
标签: .net httpwebrequest httpwebresponse