-1

我们正在尝试确定我们拥有的服务中的高 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;
           }
4

2 回答 2

1

MSDN文档:

返回值
类型:System.Int32 读入缓冲区的总字节数。如果当前没有那么多字节可用,则该字节数可能小于请求的字节数,如果已到达流的末尾,则该字节数为零 (0)。

0 表示流结束。已经定义了到达流末端的条件。您所依赖的条件可能是不可靠的并且是不必要的。

尝试

while(bytesRead != 0)

于 2013-04-30T15:46:34.607 回答
0

最好使用 StreamReader

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

// or

 while (!reader.EndOfStream)
 {
    // do read.
 }
于 2013-04-30T15:47:06.830 回答