5

This code was 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) That third line,

BindingOperations.ClearAllBindings(this.webbrowser); 

won't compile for me. What is the type of this.webbrowser? I had assumed it was WebBrowser, but the method requires System.Windows.DependencyObject.

2) In the line

var valueSwh = field.GetValue(mainwindow);

what is mainwindow? The form holding the browser control?

3) In the sixth line from the bottom,

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

what is the type of this.webbrowser.webBrowser? I see no field called webBrowser in the WebBrowser type. Is this just a typo?

Thanks for any help.

Community
  • 1
  • 1
jrvansant
  • 51
  • 3

1 Answers1

1
  1. BindingOperations is for WPF - you won't need this line if you are using WinForms.
  2. To get the mainwindow, you just need to call the WPF method GetWindow.
 var mainwindow = GetWindow(this);

3.this.webbrowser is the control ID of the WPF control (FrameworkElement.Name). By default, this is usually webbrowser1.

SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173