下面的代码中可能导致内存不足的原因是什么?我的程序运行了几个小时然后就死了。代码每次只发送/接收非常少量的数据,因此没有巨大的文件或字符串通过线路或返回。代码每隔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();
}
}
答案 0 :(得分:2)
您需要处理IDisposable类Stream
和StreamReader
:
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
responseFromServer = reader.ReadToEnd(); //IT THROWS OUT OF MEMORY HERE
}
}
实现IDisposable
的类通常具有挂起的外部资源,除非您调用Dispose()
(或者同样的事情,将其放在using
块中)。每次代码块运行时,这些类可能会泄漏内存,因此在一段时间后会出现“内存不足”异常。
答案 1 :(得分:1)
您是否检查了响应的Content-Length。也许它非常巨大。在这种情况下,您应该逐个阅读响应流