流式响应时可能的无限循环

时间:2013-04-30 15:37:50

标签: c# io stream infinite-loop

我们正在努力识别我们所拥有的服务中的高CPU使用率,并且我们认为可能会导致无限循环的一些潜在领域。下面是我们认为可能导致无限循环的代码。是否存在可能导致while循环无限期运行的特定内容?

            WebRequest request = WebRequest.Create(Url);
            request.ContentLength = formDataLength;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            using (Stream rs = request.GetRequestStream())
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                var postData = encoding.GetBytes(formData);
                rs.Write(postData, 0, postData.Length);

                string str = string.Empty;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream sm = response.GetResponseStream())
                    {
                        int totalBytesRead = 0;
                        long responseBytesToRead = 1024;
                        byte[] buffer = new byte[responseBytesToRead];
                        int bytesRead;
                        do
                        {
                            bytesRead = sm.Read(buffer, totalBytesRead, (int)(responseBytesToRead - totalBytesRead));
                            totalBytesRead += bytesRead;
                        } while (totalBytesRead < bytesRead);

                        request.Abort();
                        str = Encoding.Default.GetString(buffer);
                    }
                }
                return str;
           }

2 个答案:

答案 0 :(得分:1)

来自MSDN文档:

  

返回值
  类型:System.Int32读入的总字节数   缓冲区。这可能小于请求的字节数   许多字节当前不可用,如果结束则为零(0)   已到达流。

0表示流的结束。已经定义了到达流末尾的条件。你所依赖的条件可能是不可靠的,也是不必要的。

尝试

while(bytesRead != 0)

答案 1 :(得分:0)

最好使用StreamReader

 using (StreamReader reader = new StreamReader(response.GetResponseStream()))
...
 reader.ReadToEnd();

// or

 while (!reader.EndOfStream)
 {
    // do read.
 }