Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF element host memory leak

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, at this point, does not have a wpf control child). Only 1 host form can be opened. Every time I open the form, the application memory raises by 20Mb, which are not free when the form is closes, so, after opening the host form several times, I run out of memory!. Now, if I remove the element host from the form, the memory remains stable.

I have been running CLRProfiler and ANTS, but I have found that all the problem resides on the element host, and I haven't found any workaround for this.

The wpfHost is used out-of-the-box, just dragged from the toolbar to the winForm.

Any idea how can I solve this?

like image 784
Mg. Avatar asked Jun 16 '11 14:06

Mg.


1 Answers

if the link will break again, here is solution (copy-pasted)

Posted by KGy on 22.10.2010 at 6:12 A possible workaround: Put the following code into the Dispose or another release method of your control/form that contains the ElementHost control.

if (elementHost != null)
{
    FrameworkElement fe = elementHost.Child as FrameworkElement;
    if (fe != null)
    {
        // Memory leak workaround: elementHost.Child.SizeChanged -= elementHost.childFrameworkElement_SizeChanged;
        SizeChangedEventHandler handler = (SizeChangedEventHandler)Delegate.CreateDelegate(typeof(SizeChangedEventHandler), elementHost, "childFrameworkElement_SizeChanged");
        fe.SizeChanged -= handler;
    }
    elementHost.Child = null;
    base.Dispose(disposing);
    elementHost.Dispose();
    elementHost.Parent = null;
    elementHost = null;
}
like image 69
ncat Avatar answered Oct 28 '22 05:10

ncat