2012-03-20 32 views
3

此代碼是given by udione in response to the perennial question about the memory leak in the WebBrowser control in .Net關於udione對WebBrowser內存泄漏的解決方案

//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的字段。這只是一個錯字嗎?

感謝您的任何幫助。

回答

0
  1. BindingOperations用於WPF - 如果您使用的是WinForms,則不需要此行。
  2. 要獲取mainwindow,您只需要調用WPF方法GetWindow
var mainwindow = GetWindow(this); 

3. this.webbrowser是WPF控制(FrameworkElement.Name)的控制ID。默認情況下,這通常是webbrowser1