2013-04-30 25 views
-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; 
      } 
+0

任何理由你不使用[WebClient类](http://msdn.microsoft.com/en -us /库/ system.net.webclient.aspx)?使用它会缩短你的代码4-5行。 – dtb 2013-04-30 15:46:59

回答

1

MSDN文档:

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

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

尝试

while(bytesRead != 0)

+0

我同意,条件是......很奇怪,但不应该导致无限循环。 'bytesRead'最终应该小于或等于'totalBytesRead'。我认为别的东西正在造成滞后。 – Cemafor 2013-04-30 15:49:49

+0

@Cemafor - 我同意,很难说。我肯定会通过单元测试来运行这段代码。 – 2013-04-30 15:56:06

0

最好是使用的StreamReader

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

// or 

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