Dispose child VS2022

Antonin Hofmann 6 Reputation points
2021-12-02T09:43:21.627+00:00

This code works when it's done with VS2019 but not for VS2022. MyControl is never disposed, memory leaks...
What could be wrong?
Thx Ant

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (main.Children.Count == 0)
    {
        Console.WriteLine("Adding control");
        main.Children.Add(new MyControl() { Background = Brushes.Yellow, Width = 100, Height = 50 });
    }
    else
    {
        Console.WriteLine("Removing control");
        main.Children.RemoveAt(0);
    }

    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();
    GC.WaitForFullGCComplete();
}
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,624 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,918 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Ken Tucker 5,841 Reputation points
    2021-12-02T12:00:12.637+00:00

    What version of the .net are you using? Could MyControl have event handlers that are not being removed?

    0 comments No comments

  2. Antonin Hofmann 6 Reputation points
    2021-12-02T12:25:14.627+00:00

    VS2019 .NET Framework 4.5
    VS2022 .NET 6.0 ( tried for 4.5 too )
    ... the same project for VS19 and VS22, in the VS22 leaks and Dispose is never called

    Thx Ant

    public class MyControl : TextBlock
        {
            public byte[] data;
    
           public  MyControl()
            {
                data = new byte[10000000];
            }
            ~MyControl()
            {
                int k = 0;
                k++;       // just for brakpoint place
                Debug.WriteLine("disposed");
            }
        }