Skip to content

Commit

Permalink
[windows] fix memory leak when CollectionView.ItemsSource changes
Browse files Browse the repository at this point in the history
Fixes: #13393

Context: https://github.com/ivan-todorov-progress/maui-collection-view-memory-leak-bug

Debugging the above sample, I found that `ItemsView._logicalChildren`
grew indefinitely in size if you replace a `CollectionView`'s
`ItemsSource` over and over.

I could fix this by creating a new `internal`
`ItemsView.ClearLogicalChildren()` method and call it from the Windows
`ItemsViewHandler`.

WIP to determine if we can write a test or if this happens on any
other platforms. Android seems OK.
  • Loading branch information
jonathanpeppers committed Feb 23, 2023
1 parent 92dd968 commit 9339789
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ protected virtual void CleanUpCollectionViewSource()
CollectionViewSource.Source = null;
CollectionViewSource = null;
}
VirtualView?.ClearLogicalChildren();

if (VirtualView?.ItemsSource == null)
{
Expand Down
9 changes: 9 additions & 0 deletions src/Controls/src/Core/Items/ItemsView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,15 @@ public void RemoveLogicalChild(Element element)
VisualDiagnostics.OnChildRemoved(this, element, oldLogicalIndex);
}

internal void ClearLogicalChildren()
{
// Reverse for-loop, so children can be removed while iterating
for (int i = _logicalChildren.Count - 1; i >= 0; i--)
{
RemoveLogicalChild(_logicalChildren[i]);
}
}

internal override IReadOnlyList<Element> LogicalChildrenInternal => _logicalChildren.AsReadOnly();

internal static readonly BindableProperty InternalItemsLayoutProperty =
Expand Down

0 comments on commit 9339789

Please sign in to comment.