VS2022 C# WPF remove child dispose issue

Antonin Hofmann 6 Reputation points
2021-12-03T07:55:13.797+00:00

I can see a memory leaks when run this code compiled by VS2022.
The same project compiled by VS2019 works ok. The memory is released after some clicks.

VS2019 .NET 4.5
154733-leakok.jpg

VS2022 .NET 5.0, 6.0

154728-leaks.jpg

private void Window_MouseUp(object sender, MouseButtonEventArgs e)  
{  
    if (bAddChild)  
    {  
        // add new Control  
        baseCanvas.Children.Add(new MyControl());  
    }  
    else  
    {   
        // remove the Control  
        if (baseCanvas.Children.Count != 0)  
        {  
            baseCanvas.Children.RemoveAt(0);  
  
            baseCanvas.UpdateLayout();  
            Dispatcher.Invoke(new Action(() => { }), System.Windows.Threading.DispatcherPriority.ContextIdle, null);  
  
            GC.Collect(); // This should pick up the control removed at a previous MouseDown  
            GC.WaitForPendingFinalizers(); // Doesn't help either  
            GC.Collect();  
        }  
    }  
  
    bAddChild ^= true;  
}  
public class MyControl : UserControl  
{  
    public byte[] data;  
  
    public MyControl()  
    {  
        data = new byte[10000000];  
    }  
    ~MyControl()  
    {  
        Debug.WriteLine("disposed");  
    }  
}  
  
Developer technologies | Windows Presentation Foundation
Developer technologies | C#
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-12-03T09:14:38.607+00:00

    Try performing the tests without debugging. (Use <Ctrl+F5> to start the program). To display the memory usage, add something like this: Title = GC.GetTotalMemory(true).ToString("#,###").

    If you want to use the Debugger in such tests, then try unchecking the "Enable XAML Hot Reload" checkbox in Tools menu, Options dialog, Debugging, XAML Hot Reload.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.