Repository navigation
Description
Problem
In Debug builds of Uno.UI, every ItemsView that uses the default style is retained for the lifetime of the process.
ItemsView.OnLayoutChangedDbg() (compiled under #if DEBUG, invoked from OnPropertyChanged whenever LayoutProperty changes) subscribed two instance-method handlers to the incoming Layout:
layout.MeasureInvalidated += OnLayoutMeasureInvalidatedDbg;
layout.ArrangeInvalidated += OnLayoutArrangeInvalidatedDbg;The default ItemsView style (src/Uno.UI/UI/Xaml/Controls/ItemsView/ItemsView.xaml) sets Layout through a <Setter> whose value is a single <controls:StackLayout /> element. A Setter value is one object shared by every ItemsView using that style, and it lives for the whole process. Since the handlers are instance methods, each subscription stores a delegate whose target is the ItemsView — so the process-lifetime shared StackLayout ends up holding a strong reference to every ItemsView ever constructed.
Nothing ever removes those subscriptions for a discarded control:
- The
DisposableActionrevokers (m_layoutMeasureInvalidatedDbg/m_layoutArrangeInvalidatedDbg) are only disposed insideOnLayoutChangedDbgitself, i.e. whenLayoutPropertychanges again — which never happens for a control that has simply been removed from the tree and dropped. - Neither
~ItemsView()norOnUnloadeddisposes them — and the finalizer can never run anyway, because the rooted sharedLayout's delegate keeps the control strongly reachable. OnUnloadedwould not be a reliable fix either:Unloadeddoes not fire when a visual tree is torn down wholesale (e.g. window content swapped, or a hosted app being unloaded).
The handlers themselves are empty no-ops — their trace calls are commented out — so the subscriptions provided no diagnostic value at all.
Impact
- Any Debug-built app: every
ItemsView(plus everything it references —ItemsSource,DataContext, item containers, its element subtree) leaks for the life of the process. Repeated navigation to pages containing anItemsViewgrows the heap without bound. - Hosts using collectible
AssemblyLoadContexts (designer-style hosts / plugin hosts that load preview apps into a collectible ALC while sharing the framework assemblies from the default ALC): the sharedStackLayoutlives in the default ALC forever, and via the leakedItemsViewit holdsDataContext/ItemsSource/ template objects from the collectible ALC. This single edge pins the entire unloaded ALC —AssemblyLoadContext.Unload()never completes collection. Found during a ClrMD dump campaign attributing ALC pins; the GC-root path was: default-styleStackLayout→MeasureInvalidateddelegate invocation list →ItemsView→ app objects in the collectible ALC. - Release builds are unaffected (
#if DEBUGcode is compiled out), which is also why Release CI never caught this.
Root cause
Instance-method event subscription onto an object with a longer lifetime than the subscriber (a style-Setter singleton), with no unsubscription path on the subscriber's teardown. Classic publisher-outlives-subscriber leak, gated behind #if DEBUG.
Reproduction (self-contained, this repo)
- Build
Uno.UIand the SamplesApp in Debug configuration (soDEBUGis defined forUno.UI). - Run the existing runtime test
Given_FrameworkElement_And_Leak.When_Add_Removefor theItemsViewdata row (src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_FrameworkElement_And_Leak.cs,[ActivatableDataRow(typeof(ItemsView), 15)]). - Before the fix the test fails: after removing all 15 instances and running repeated
GC.Collect()/ finalizer / idle cycles for up to 30 s, theWeakReferences to theItemsViewinstances (and their subtrees) never die.
Minimal manual variant:
var wr = new WeakReference(null);
void Create()
{
var iv = new Microsoft.UI.Xaml.Controls.ItemsView();
wr.Target = iv;
rootContainer.Content = iv; // default style applies -> Layout Setter assigns shared StackLayout
// -> OnPropertyChanged(LayoutProperty) -> OnLayoutChangedDbg subscribes
rootContainer.Content = null; // removed; no path ever unsubscribes
}
Create();
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();
// Debug build, before fix: wr.IsAlive == true, foreverALC variant: load an app assembly that instantiates an ItemsView into a collectible AssemblyLoadContext (framework assemblies shared from the default ALC), unload the ALC, GC — a WeakReference<AssemblyLoadContext> stays alive indefinitely.
Red/green test definition (already written)
The regression guard already exists in-repo and requires no new code:
- Test:
Uno.UI.RuntimeTests.Tests.Windows_UI_Xaml.Given_FrameworkElement_And_Leak.When_Add_Remove, data row[ActivatableDataRow(typeof(ItemsView), 15)](line 115). - Arrange: sets a
ContentControlas window content; materializes 15ItemsViewinstances (Fluent default style, then repeats under UWP styles), tracking each createdDependencyObjectwithWeakReference<DependencyObject>. - Act: removes each instance from the tree, then loops
GC.Collect()/GC.WaitForPendingFinalizers()/ dispatcher-idle waits for up to 30 seconds. - Assert: every tracked weak reference must be collected; any survivor fails the test with a dump of the retained objects.
- Red: fails on a Debug-configuration
Uno.UIbuild before the fix (shared default-styleStackLayoutretains all instances through theMeasureInvalidated/ArrangeInvalidateddelegates). Green: passes after the fix. - Caveat: the buggy code is
#if DEBUG-only, so the row only exercises the bug whenUno.UIis compiled withDEBUGdefined; Release legs compile the code out and were always green.
Activity
fix(ItemsView): remove now-unused DEBUG layout-invalidation handlers
fix(ItemsView): remove now-unused DEBUG layout-invalidation handlers