我目前正在开发一个应用程序,我在 WinForms 主机中使用 WinForms WebBrowser 控件。问题是即使我关闭浏览器并处理所有内存似乎没有被释放的东西。
我找到了这篇文章,看起来 udione 的答案可能就是我想要的。问题是我不确定如何让它通过 WPF 与 WinForms 控件一起工作。
如何解决 .NET Webbrowser 控件中的内存泄漏问题?
这也是我改变它的地方,但它似乎没有奏效。我不确定 this.webbrowser.webBrowser
public void DisposeWebBrowser(System.Windows.Forms.WebBrowser browser)
{
//dispose to clear most of the references
browser.Dispose();
//REMOVED THIS LINE
//BindingOperations.ClearAllBindings(browser.);
//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);
//CHANGED THIS LINE
//var valueSwh = field.GetValue(mainwindow); <-- OLD LINE
var valueSwh = field.GetValue(GetWindow(this));
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);
//CHANGED THIS LINE
//if (object.ReferenceEquals(sinkObject.GetValue(entry), this.webbrowser.webBrowser)) <-- OLD LINE
if (object.ReferenceEquals(sinkObject.GetValue(entry), browser))
{
ilist.Remove(entry);
}
}
}
}
关于如何让它工作或更好地处理问题的任何想法?