WPF WindowsFormsHost memory leak

818 Views Asked by At

I've got a WPF TabControl containing a WindowsFormsHost in each TabPage. User can add and remove TabPage as needed: when the user removes a Tab, I obviously dispose the child control and the host itself.

Using VS Diagnostic Tool, I've found a leak of WindowsFormsHost:

leak

I've also reproduced the issue using an empty WindowsFormsHost, with no inner child, tested with framework 4.0 and 4.7.2. Something like:

<Grid>
    <WindowsFormsHost/>

How can I solve? GC.Collect() does not do the trick.

1

There are 1 best solutions below

1
Fabio On

Solved removing the WindowsFormsHost element from parent layout:

public class WindowsFormsHostEx : WindowsFormsHost
{
    public WindowsFormsHostEx() { }

    protected override void Dispose(bool disposing)
    {
        if (this.Child != null && this.Child is IDisposable)
            (this.Child as IDisposable).Dispose();

        this.Child = null;

        //magic line!!!
        (this.Parent as Panel).Children.Remove(this);

        base.Dispose(disposing);
    }
}