[英]Memory leak when using HttpWebRequest object in ASP.NET site
这是我的课:
public class HttpRequestHelper
{
public static string GetRequestText(string url, string method, string referer, string postData, int timeout = 50000, string userAgent = null, string proxy = null)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
request.Method = method;
request.Timeout = timeout;
if (!string.IsNullOrEmpty(proxy))
request.Proxy = new System.Net.WebProxy(proxy);
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
if (!userAgent.IsNullOrEmptyText())
{
request.UserAgent = userAgent;
}
if (!string.IsNullOrEmpty(referer))
{
request.Referer = referer;
}
if (method == "POST")
{
if (!string.IsNullOrEmpty(postData))
{
request.ContentLength = postData.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
}
else request.ContentLength = 0;
}
string result = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
return result;
}
}
正常情况下,我的网站需要大约170mb的内存(数据库中大约有4万条记录)。 但是,当我调用GetRequestText
函数时,内存可达1Gb。 我不知道为什么? 有什么想法或解决方案吗?
谢谢前进!
这可能是试图为您智能管理内存的.NET框架...在任务管理器中报告的内存实际上不是您的应用程序使用的内存,而是分配给您的应用程序使用的内存。 尝试在此方法的末尾添加GC.Collect()
调用-如果将您的内存减小到相对正常的大小,则无需担心。 如果没有,那么实际上您确实会以不释放资源或其他方式释放对象的形式出现内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.