OutOfMemoryException读取响应流

时间:2012-10-20 18:02:13

标签: c# memory-management file-io out-of-memory

下面的代码中可能导致内存不足的原因是什么?我的程序运行了几个小时然后就死了。代码每次只发送/接收非常少量的数据,因此没有巨大的文件或字符串通过线路或返回。代码每隔3秒左右从服务器发送和接收。

private void Read()
{
    string postData = "Name=John"
    using (HttpWebResponse response = SendRequest(new Uri(@"someWebSitehere"), postData))
    {
         Stream stream = response.GetResponseStream();
         StreamReader reader = new StreamReader(stream);
         responseFromServer = reader.ReadToEnd();  IT THROWS OUT OF MEMORY HERE
         stream.Close();
    }
}

private HttpWebResponse SendRequest(Uri uri, string postData)
{
    lock (SendRequestLock)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);

        req.Method = "POST";
        req.CookieContainer = new CookieContainer();
        req.Proxy = null;
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] byte1 = encoding.GetBytes(postData);

        // Set the content type of the data being posted.
        req.ContentType = "application/x-www-form-urlencoded";

        // Set the content length of the string being posted.
        req.ContentLength = byte1.Length;

        req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)";
        req.Method = "POST";
        req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        req.Headers.Add("Accept-Language: en-us,en;q=0.5");
        req.Headers.Add("Accept-Encoding: gzip,deflate");
        req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
        req.KeepAlive = true;
        req.Headers.Add("Keep-Alive: 300");
        using (Stream stream = req.GetRequestStream())
        {
            stream.Write(byte1, 0, byte1.Length);
        }
        return (HttpWebResponse)req.GetResponse();
    }
}

2 个答案:

答案 0 :(得分:2)

您需要处理IDisposable类StreamStreamReader

using (Stream stream = response.GetResponseStream())
{
    using (StreamReader reader = new StreamReader(stream)) 
    {
        responseFromServer = reader.ReadToEnd();  //IT THROWS OUT OF MEMORY HERE
    }
}

实现IDisposable的类通常具有挂起的外部资源,除非您调用Dispose()(或者同样的事情,将其放在using块中)。每次代码块运行时,这些类可能会泄漏内存,因此在一段时间后会出现“内存不足”异常。

值得一读MSDN's notes on IDisposable

答案 1 :(得分:1)

您是否检查了响应的Content-Length。也许它非常巨大。在这种情况下,您应该逐个阅读响应流