1

这是我的课:

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 内存(数据库中大约有 40k 条记录)。但是当我调用GetRequestText函数时内存高达 1Gb 内存。我不知道为什么?对此有任何想法或解决方案吗?

提前谢谢!

4

1 回答 1

2

这可能是 .NET 框架试图为您智能地管理内存...在任务管理器中报告的内存实际上不是您的应用程序使用的内存,而是分配给您的应用程序使用的内存。尝试GC.Collect()在此方法的末尾添加一个调用 - 如果它使您的内存恢复到相对正常的大小,那么您无需担心。如果没有,那么您实际上确实存在可能的内存泄漏,其形式为未释放资源的对象或其他形式。

于 2013-06-02T18:48:14.333 回答