Regarding udione's solution for WebBrowser memory leak
This code was asked by udione in response to a longstanding question about memory leaks 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) Third line,
BindingOperations.ClearAllBindings(this.webbrowser);
won't compile for me. What is the type this.webbrowser
? I assumed it was WebBrowser
, but this method requires System.Windows.DependencyObject
.
2) In line
var valueSwh = field.GetValue(mainwindow);
what is it mainwindow
? Form containing browser control?
3) In the sixth line from the bottom
if (object.ReferenceEquals(sinkObject.GetValue(entry), this.webbrowser.webBrowser))
what is the type this.webbrowser.webBrowser
? I don't see the type field WebBrowser
in the type WebBrowser
. Is this just a typo?
Thanks for any help.
source to share
-
BindingOperations
for WPF - you don't need this line if you are using WinForms. - To get
mainwindow
, you just need to call the WPF methodGetWindow
.
var mainwindow = GetWindow(this);
3. this.webbrowser
is the id of the WPF control ( FrameworkElement.Name
). By default, this is normal webbrowser1
.
source to share