Skip to content

ItemsView (Debug builds): DEBUG-only layout diagnostics let the default-style shared StackLayout retain every ItemsView — leaks controls and pins collectible AssemblyLoadContexts #23631

Closed

Description

@nickrandolph

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 DisposableAction revokers (m_layoutMeasureInvalidatedDbg / m_layoutArrangeInvalidatedDbg) are only disposed inside OnLayoutChangedDbg itself, i.e. when LayoutProperty changes again — which never happens for a control that has simply been removed from the tree and dropped.
  • Neither ~ItemsView() nor OnUnloaded disposes them — and the finalizer can never run anyway, because the rooted shared Layout's delegate keeps the control strongly reachable.
  • OnUnloaded would not be a reliable fix either: Unloaded does 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 an ItemsView grows 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 shared StackLayout lives in the default ALC forever, and via the leaked ItemsView it holds DataContext / 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-style StackLayout → MeasureInvalidated delegate invocation list → ItemsView → app objects in the collectible ALC.
  • Release builds are unaffected (#if DEBUG code 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)

  1. Build Uno.UI and the SamplesApp in Debug configuration (so DEBUG is defined for Uno.UI).
  2. Run the existing runtime test Given_FrameworkElement_And_Leak.When_Add_Remove for the ItemsView data row (src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_FrameworkElement_And_Leak.cs, [ActivatableDataRow(typeof(ItemsView), 15)]).
  3. Before the fix the test fails: after removing all 15 instances and running repeated GC.Collect() / finalizer / idle cycles for up to 30 s, the WeakReferences to the ItemsView instances (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, forever

ALC 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 ContentControl as window content; materializes 15 ItemsView instances (Fluent default style, then repeats under UWP styles), tracking each created DependencyObject with WeakReference<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.UI build before the fix (shared default-style StackLayout retains all instances through the MeasureInvalidated/ArrangeInvalidated delegates). Green: passes after the fix.
  • Caveat: the buggy code is #if DEBUG-only, so the row only exercises the bug when Uno.UI is compiled with DEBUG defined; Release legs compile the code out and were always green.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions