0

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.

Fabio
  • 77
  • 6
  • What specifically makes this a "leak"? Maybe the garbage collector just hasn't collected it yet. – StayOnTarget Nov 16 '20 at 15:15
  • Leak because after 15/20 minutes that memory should be released... – Fabio Nov 16 '20 at 15:39
  • Maybe. You should add some garbage collection calls just for debugging purposes to see if that causes the memory to be released or not. If it does not, I agree that sounds like a leak. But if it DOES get released, then its just a case of the GC taking its time. e.g. you will want to add something like ` GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();` ... – StayOnTarget Nov 16 '20 at 15:42
  • @UuDdLrLrSs no way, still there – Fabio Nov 16 '20 at 15:50
  • That's good info. I think you should edit the question with the code you used to test this. – StayOnTarget Nov 16 '20 at 15:51

1 Answers1

3

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);
    }
}
Fabio
  • 77
  • 6