Dispose child VS2022

Antonin Hofmann 6 Reputation points

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 });
        Console.WriteLine("Removing control");

    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
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
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

    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

    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];
                int k = 0;
                k++;       // just for brakpoint place