我们正在尝试确定服务中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;
}
任何理由你不使用[WebClient类](http://msdn.microsoft.com/en -us /库/ system.net.webclient.aspx)?使用它会缩短你的代码4-5行。 – dtb 2013-04-30 15:46:59