关于udione对WebBrowser内存泄漏的解决方案

时间:2012-03-20 14:25:48

标签: .net wpf memory browser memory-leaks

此代码为given by udione in response to the perennial question about the memory leak in the WebBrowser control in .Net

//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); 
        } 
    } 
}  

1)第三行,

BindingOperations.ClearAllBindings(this.webbrowser); 

不会为我编译。 this.webbrowser的类型是什么?我假设它是WebBrowser,但该方法需要System.Windows.DependencyObject

2)在行

var valueSwh = field.GetValue(mainwindow);

什么是mainwindow?持有浏览器控件的表单?

3)在底部的第六行,

if (object.ReferenceEquals(sinkObject.GetValue(entry), this.webbrowser.webBrowser))  

this.webbrowser.webBrowser的类型是什么?我在webBrowser类型中看不到名为WebBrowser的字段。这只是一个错字吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

  1. BindingOperations适用于WPF - 如果您使用的是WinForms,则不需要此行。
  2. 要获得mainwindow,您只需要调用WPF方法GetWindow
  3.  var mainwindow = GetWindow(this);
    

    3. this.webbrowser是WPF控件的控件ID(FrameworkElement.Name)。默认情况下,通常为webbrowser1