I\'m having a strange memory leak using element host on windows forms. I have a main form, which opens another form, the one that only haves the elementhost control on it (which
The primary cause of "memory leaks" in .NET applications is event handlers. If object A handles an event raised by object B, object A can go out of scope and it won't be destroyed, because even though your code doesn't retain a reference to it, object B does.
In WinForms, some UI objects (ToolStripButton
is a good example) register with Windows to handle theme-change events. Windows holds a reference to them so that it can tell them if the user changes the theme. Annoyingly, these objects don't unregister if the form they're on closes, with the result that their form gets destroyed but they don't.
So how the heck do you destroy one of these objects? In the case of ToolStripButton
, setting Visible
to false
does the trick. It turns out that toggling Visible
also toggles whether or not the control handles theme-change events. So if you set Visible
to false
, the control unregisters, and then when it goes out of scope it actually can get destroyed.
Maybe that will help with ElementHost
, for the same or a similar reason. It's hard to tell, because as you'll find if you dig into this issue, it's not exactly, you know, documented.