以下代码在Windows窗体中运行,创建一个WebBrowser控件并导航到许多URL。每次将URL导航到应用程序消耗的内存增加时,似乎永远不会释放。在我的情况下,消耗的内存从大约10 Mb上升到大约45 Mb导航仅4个文档。我需要浏览几百个文档,这些文档会快速导致所有物理内存的使用。
如何释放WebBrowser控件使用的资源?
private void ProcessDocs()
{
Random rnd = new Random();
DateTime dtWaitUntil = DateTime.Now;
string[] arrInputUrl = new string[] { "http://www.google.co.uk/", "http://www.google.com/", "http://www.yahoo.com/", "http://www.amazon.co.uk/" };
for (int i = 0; i < arrInputUrl.Length; i++)
{
using (WebBrowser objWebBrowser = new WebBrowser())
{
string txtInputUrl = arrInputUrl[i];
tboxTestingOutput.Text += "\r\n" + txtInputUrl;
objWebBrowser.ScriptErrorsSuppressed = true;
objWebBrowser.Navigate(txtInputUrl);
//Should do this a better way, but, wait 10 secs for document to complete.
//Would use objWebBrowser.DocumentCompleted event
//but it seems to fire several times per document load!!!
dtWaitUntil = DateTime.Now.AddSeconds(10);
do
{
Application.DoEvents();
} while (DateTime.Now < dtWaitUntil);
//Do whatever I need to with the document contents
//...
//...
}
}
tboxTestingOutput.Text += "\r\nFinished";
}
答案 0 :(得分:0)
虽然我不会完全推荐它,但P / Invoke SetProcessWorkingSetSize为-1应该强制清空进程工作集,例如:
[DllImport("kernel32.dll")]
static extern bool SetProcessWorkingSetSize(IntPtr handle, int minSize, int maxSize);
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle,-1,-1);
在这里阅读更多内容:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686234(v=vs.85).aspx