What version of the .net are you using? Could MyControl have event handlers that are not being removed?
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 });
}
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();
}
2 answers
Sort by: Most helpful
-
-
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 calledThx 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"); } }