2013-12-11 65 views
3

我有webBrowser控件中的内存泄漏问题。 我发现这个线程:WebBrowser控制内存泄漏

How to get around the memory leak in the .NET Webbrowser control?

这:

//dispose to clear most of the references 
this.webbrowser.Dispose(); 
BindingOperations.ClearAllBindings(this.webbrowser); 

//using reflection to remove one reference that was not removed with the dispose 
var field = typeof(System.Windows.Window).GetField("_swh", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); 

var valueSwh = field.GetValue(mainwindow); 

var valueSourceWindow = valueSwh.GetType().GetField("_sourceWindow", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(valueSwh); 

var valuekeyboardInput = valueSourceWindow.GetType().GetField("_keyboardInputSinkChildren", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(valueSourceWindow); 

System.Collections.IList ilist = valuekeyboardInput as System.Collections.IList; 

lock(ilist) 
{ 
    for (int i = ilist.Count-1; i >= 0; i--) 
    { 
     var entry = ilist[i]; 
     var sinkObject = entry.GetType().GetField("_sink", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); 
     if (object.ReferenceEquals(sinkObject.GetValue(entry), this.webbrowser.webBrowser)) 
     { 
      ilist.Remove(entry); 
     } 
    } 
} 

但我使用Windows.Forms的无WPF窗口,我有这个代码转换为我的需求问题。有人能帮助我吗?

+0

你确定的WinForms有泄漏呢? – SLaks

+0

是的。我正在监视我的应用正在使用的物理内存。并且正在增长和增长(并不快但仍然)。我的应用程序只是一个web浏览器导航到大量的页面。 – Yozer

+0

确切的问题是什么妨碍您使用此解决方案? – nestedloop

回答

3

我们在几个应用程序中使用了Chromium。这使我们能够在WinXP中运行HTML 5。由于webBrowser控件使用安装的操作系统的IE,因此无法使用大部分更好的HTML/Javascript。微软不支持WinXP的IE,因此应用程序只能访问旧版本的IE。

如果您使用Chromium的CEFSharp版本,您甚至可以编译进一步的mods和辅助导航,从而为您提供IE不支持的改进的嵌入式通信。

的代码是非常简单的,有几个例子,但只是看:

InitializeComponent(); 
Text = "CefSharp"; 

web_view = new WebView("https://github.com/perlun/CefSharp", new BrowserSettings()); 
web_view.Dock = DockStyle.Fill; 
toolStripContainer.ContentPanel.Controls.Add(web_view); 
//even setup the console to log to a Textbox for debugging by setting up a Handler. 
web_view.ConsoleMessage += new CefSharp.ConsoleMessageEventHandler(ConsoleMessageHandler); 
1

您是否考虑过使用其他网络浏览器控件?那里有很多!我觉得chromium是一个很好的选择,请查看this question的替代方案。

2

我们前段时间遇到过这个问题......都无济于事。

要解决这个问题并将应用程序的内存消耗保持在合理的水平,我们决定将应用程序分成两种进程,一种用于主窗口,另一种用于承载WebBrowserControl的子进程。然后,设计一个管道协议(或RMI/RPC-like)来将事件从主窗口传递给子进程,反之亦然。

这样做,您可以设计一个循环策略,使用浏览器进程池和背景kill-and-spawn策略来控制内存消耗。