[ios/catalyst] fix memory leak with CollectionView
Fixes: https://github.com/dotnet/maui/issues/20710 Context: https://github.com/marco-skizza/MauiCollectionView
Testing the sample above, you can see a memory leak when setting up a CollectionView's DataTemplate in XAML, but it appears to work just fine with C#.
Using dotnet-gcdump with a Release build of the app, I see:
You can cause the C# version to leak, if you make the lambda an instance method:
- https://github.com/jonathanpeppers/iOSMauiCollectionView/commit/3e5fb021fee3b512d8163c53224e17b76c3789c2
XAML just happens to use an instance method, no matter if XamlC is on/off.
I was able to reproduce this in CollectionViewTests.iOS.cs by making the CollectionView look like a "user control" and create an instance method.
There is a "cycle" that causes the problem here:
-
Microsoft.Maui.Controls.Handlers.Items.VerticalCell(note this is aUICollectionViewCell) -> -
DataTemplate-> -
Func<object>-> -
PageXamlLeak(orPageCsOkw/ my change) -> -
CollectionView-> -
Microsoft.Maui.Controls.Handlers.Items.VerticalCell
The solution being to make TemplatedCell (which is a subclass of VerticalCell) hold only a WeakReference to the DataTemplate.
With this change in place, the test passes.
CellsDoNotLeak test is failing on Catalyst (pass on iOS).
CellsDoNotLeaktest is failing on Catalyst (pass on iOS).
What is weird: the test passes when I run it by itself, but not when running the full suite.
Retested the original sample app, the change seems to be working:
2024-04-16 14:39:15.575 MauiCollectionView[50559:5841573] Memory: 9498688
2024-04-16 14:39:21.874 MauiCollectionView[50559:5841573] Memory: 9690168
2024-04-16 14:39:22.810 MauiCollectionView[50559:5841573] Memory: 9868400
2024-04-16 14:39:23.485 MauiCollectionView[50559:5841584] ~PageXamlLeak() called
2024-04-16 14:39:23.487 MauiCollectionView[50559:5841573] Memory: 9870832
2024-04-16 14:39:24.193 MauiCollectionView[50559:5841573] Memory: 9897776
2024-04-16 14:39:24.872 MauiCollectionView[50559:5841584] ~PageXamlLeak() called
2024-04-16 14:39:24.875 MauiCollectionView[50559:5841573] Memory: 9879648
2024-04-16 14:39:25.576 MauiCollectionView[50559:5841573] Memory: 9901808
2024-04-16 14:39:26.257 MauiCollectionView[50559:5841584] ~PageCsOk() called
2024-04-16 14:39:26.260 MauiCollectionView[50559:5841573] Memory: 9883584
2024-04-16 14:39:26.943 MauiCollectionView[50559:5841573] Memory: 9908720