简体   繁体   English

C#:处理HttpWebResponse超时问题

[英]C# : Dealing with HttpWebResponse timeout problems

I have a big problem dealing with data I try to download in my Application over the internet via HttpWebResponse. 处理我试图通过HttpWebResponse在我的应用程序中下载的数据时遇到了很大的问题。 My code looks like that: 我的代码看起来像这样:

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++;
         }
    }
}

This code runs in a few instances in separated threads so it's a little bit hard to debug. 此代码在分离的线程中的几个实例中运行,因此调试有点困难。 The problem is this method got stuck and I blame it on the poor connection to the data. 问题是这种方法卡住了,我把它归咎于与数据的连接不良。

As you can see I already set a timeout and was hoping the code would just terminate after the timeout time has expired. 正如您所看到的,我已经设置了超时,并且希望代码在超时时间到期后才会终止。 It does not! 它不是! At least not all the time. 至少不是所有的时间。 Sometimes I get a WebException/Timeout but a few times it just got stuck. 有时我得到一个WebException / Timeout但有几次它只是卡住了。

What is a timeout exactly? 什么是超时? When is it called? 什么时候打电话? Lets say the HttpWebResponse starts to receive data but it got stuck somewhere in the middle of transmission. 让我们说HttpWebResponse开始接收数据,但它在传输过程中卡在某处。 Do I get a timeout? 我有超时吗? For me it looks like I don't because my application got stuck too and no timeout exception is raised. 对我来说,看起来我没有,因为我的应用程序也被卡住了,并且没有引发超时异常。

What can I do to patch this up or how can I get further information about what is going wrong here? 我可以做些什么来修补此问题,或者如何获得有关此处出现问题的更多信息?

Try setting HttpWebRequest.ReadWriteTimeout Property 尝试设置HttpWebRequest.ReadWriteTimeout属性

The number of milliseconds before the writing or reading times out. 写入或读取超时前的毫秒数。 The default value is 300,000 milliseconds (5 minutes). 默认值为300,000毫秒(5分钟)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM