我在处理数据时遇到了很大的问题,我尝试通过 HttpWebResponse 通过 Internet 在我的应用程序中下载该数据。我的代码看起来像这样:
myWebRequest.Timeout = 10000;
using (HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse())
{
using (Stream ReceiveStream = myWebResponse.GetResponseStream())
{
Encoding encode = Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(ReceiveStream, encode);
// Read 1024 characters at a time.
Char[] read = new Char[1024];
int count = readStream.Read(read, 0, 1024);
int break_counter = 0;
while (count > 0 && break_counter < 10000)
{
String str = new String(read, 0, count);
buffer += str;
count = readStream.Read(read, 0, 1024);
break_counter++;
}
}
}
这段代码在几个独立的线程中运行,因此调试起来有点困难。问题是这种方法卡住了,我将其归咎于与数据的连接不良。
如您所见,我已经设置了超时,并希望代码会在超时时间到期后终止。它不是!至少不是所有时候。有时我会遇到 WebException/Timeout,但有几次它只是卡住了。
究竟什么是超时?什么时候调用? 假设 HttpWebResponse 开始接收数据,但它在传输过程中卡在了某个地方。我会超时吗?对我来说,我似乎没有,因为我的应用程序也卡住了,没有引发超时异常。
我能做些什么来修补这个问题,或者我如何才能获得有关这里出了什么问题的更多信息?
最佳答案
尝试设置 HttpWebRequest.ReadWriteTimeout Property
The number of milliseconds before the writing or reading times out. The default value is 300,000 milliseconds (5 minutes).
关于C# : Dealing with HttpWebResponse timeout problems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2462352/