[英]How to release memory whilst navigating web documents using a Windows.Forms.WebBrowser control
The following code, run in a windows form, creates a WebBrowser control and navigates to a number of URLs. 以下代码以Windows窗体运行,创建一个WebBrowser控件并导航到许多URL。 Each time a URL is navigated to the memory consumed by the application increases and never seems to get released.
每次将URL导航到应用程序占用的内存时,URL都会增加,并且似乎永远不会被释放。 In my case the memory consumed rises from ~10 Mb to ~45 Mb navigating just 4 documents.
在我的情况下,仅浏览4个文档,消耗的内存从〜10 Mb增加到〜45 Mb。 I need to navigate several hundred documents which quickly causes all the physical memory to be used.
我需要浏览几百个文档,这很快导致所有物理内存被使用。
How do I release the resources used by the WebBrowser control? 如何释放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";
}
Although I wouldn't completely recommend it, P/Invoke SetProcessWorkingSetSize with -1 should force an empty of the process working set, for example: 尽管我不会完全推荐它,但是P / Invoke SetProcessWorkingSetSize -1应该强制清空进程工作集,例如:
[DllImport("kernel32.dll")]
static extern bool SetProcessWorkingSetSize(IntPtr handle, int minSize, int maxSize);
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle,-1,-1);
Read more here: 在这里阅读更多:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686234(v=vs.85).aspx http://msdn.microsoft.com/zh-CN/library/windows/desktop/ms686234(v=vs.85).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.