2012-03-20 5 views
3

このコードはgiven by udione in response to the perennial question about the memory leak in the WebBrowser control in .Netでした。Webブラウザーのメモリリークに対するudioneのソリューションについて

//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)、第3ライン、

BindingOperations.ClearAllBindings(this.webbrowser); 

は私のためにコンパイルされません。 this.webbrowserの種類は何ですか?私はそれが WebBrowserと仮定していましたが、方法は System.Windows.DependencyObjectが必要です。 mainwindowで何行で

2)

var valueSwh = field.GetValue(mainwindow); 

?ブラウザコントロールを保持するフォーム? this.webbrowser.webBrowserの種類が何であるか下から6行目で

3)、

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

WebBrowserタイプではwebBrowserというフィールドはありません。これはちょうどタイプミスですか?

ありがとうございました。

答えて

0
  1. BindingOperationsはWPF用です.WindFormsを使用している場合は、この行は必要ありません。
  2. mainwindowを取得するには、WPFメソッドGetWindowを呼び出すだけです。
var mainwindow = GetWindow(this); 
this.webbrowser

3 WPFコントロール(FrameworkElement.Name)の制御IDです。デフォルトでは、これは通常webbrowser1です。

関連する問題