流响应时可能出现无限循环

本文关键字:无限循环 响应 | 更新日期: 2023-09-27 18:11:44

我们正在努力确定我们所拥有的服务的高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;
           }

流响应时可能出现无限循环

来自MSDN文档:

返回值
类型:系统。Int32总的读字节数缓冲。这可以小于所请求的字节数那么多字节当前不可用,如果结束则为零(0)流已到达。

0表示流结束。到达流终点的条件已经确定。你所依赖的条件可能是不可靠的,而且是不必要的。

while(bytesRead != 0)

最好使用StreamReader

 using (StreamReader reader = new StreamReader(response.GetResponseStream()))
...
 reader.ReadToEnd();
// or
 while (!reader.EndOfStream)
 {
    // do read.
 }