【问题标题】:Regarding udione's solution to the WebBrowser memory leak关于udione对WebBrowser内存泄漏的解决方案
【发布时间】:2012-04-05 00:46:43
【问题描述】:

这个代码是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 的字段。这只是一个错字吗?

感谢您的帮助。

【问题讨论】:

    标签: .net wpf memory browser memory-leaks


    【解决方案1】:
    1. BindingOperations 用于 WPF - 如果您使用 WinForms,则不需要此行。
    2. 要获取mainwindow,只需调用WPF方法GetWindow即可。
     var mainwindow = GetWindow(this);
    

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

    【讨论】:

      猜你喜欢
      • 2011-08-14
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 2013-04-01
      相关资源
      最近更新 更多