1

什么可能导致下面代码中的内存不足异常?我的程序运行了几个小时然后死了。该代码每次只发送/接收非常少量的数据,因此没有大文件或字符串通过线路或返回。代码每 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();
    }
}
4

2 回答 2

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 关于 IDisposable 的注释

于 2012-10-20T18:04:35.310 回答
1

您是否检查了响应的内容长度。也许它非常巨大。在这种情况下,您应该逐部分阅读响应流

于 2012-10-20T18:21:21.137 回答