.NET WebBroswer内存释放

  最近写的小说爬取工具遇到了性能瓶颈,使用多个Webbroswer控件预加载多个网页,内存会不断增加,达到400M左右,不能忍。

失败的例子

  首先尝试把Webbroswer对象置为null,wb=null,等待GC自动回收,毫无效果。

            WebBrowser wb = new WebBrowser();
            wb.DocumentCompleted += delegate(object sender, WebBrowserDocumentCompletedEventArgs args)
            {
                if (wb != null && IsBroswerOK(wb))
                {
                    Html = wb.DocumentText;
                    //删除浏览器
                    wb = null;
                }
            };
            wb.Navigate(c.Url);

  而后尝试加入一个强制垃圾回收

System.GC.Collect();

  依然无效

成功的例子

  果然自己还是靠不住,老老实实开谷歌搜,终于在MSDN上找到解决方案。原帖点我

首先在类的开头导入系统内核

        [DllImport("KERNEL32.DLL", EntryPoint = "SetProcessWorkingSetSize", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern bool SetProcessWorkingSetSize(IntPtr pProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize);
        [DllImport("KERNEL32.DLL", EntryPoint = "GetCurrentProcess", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern IntPtr GetCurrentProcess();

在释放浏览器内存时调用

                    //删除浏览器
                    wb = null;
                    //清理内存
                    IntPtr pHandle = GetCurrentProcess();
                    SetProcessWorkingSetSize(pHandle, -1, -1);

值得注意的是,该方法不宜经常使用

它带来一个很严重的弊端,操作系统为了实现限制内存的大小,会不断的进行内存与虚拟内存之间的转换,反而大大加重了操作系统的负担,所以不宜常用。

原文地址:https://www.cnblogs.com/singlex/p/4658294.html