当我反复使用WebBrowser.Document.DomDocument时,我得到OutOfMemoryException

时间:2015-04-23 16:21:22

标签: c# dom webbrowser-control

当我反复使用WebBrowser.Document.DomDocument时,我得到OutOfMemoryException。

在我的控制台应用中,我有以下代码:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace Test
{
    public class OutOfMem
    {
        static private List<string> List = new List<string>();
        private const string _url = "http://www.google.com";

        static void Main(string[] args)
        {
            // in i == 86 out of mem exception
            for (int i = 0; i < 100; i++)
            {
                Thread t = new Thread(new ThreadStart(TestFunc));
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
                t.Join();
                t = null;
            }
        }

        private static void TestFunc()
        {
            System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
            wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
            wb.Navigate(_url);

            while (wb.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();

            wb.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);

            mshtml.HTMLDocument doc = wb.Document.DomDocument as mshtml.HTMLDocument;

            // this throws out of memory exception when i == 86 why?
            string html = doc.documentElement.outerHTML;
            doc.close();

            // trying to release everything
            wb.Dispose();
            GC.Collect();
            GC.Collect();
        }

        private static void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlDocument document = ((WebBrowser)sender).Document;
            mshtml.HTMLDocument doc = document.DomDocument as mshtml.HTMLDocument;
            List.Add(doc.documentElement.outerHTML);
            doc.close();
        }
    }
}

我得到OutOfMemory Exception。我不知道应该释放什么,但我不知道。程序似乎没有占用太多内存(只需通过Windows任务管理器检查)。我在W7下使用VS 2012。

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

您打算在没有清除列表的情况下通过循环调用List.Add进行每次迭代吗?通过运行86,您有86个outerHTML副本。