Skip to content

[leak-scan] Picker.ItemsSource leaks the control via strong CollectionChanged subscription (no weak proxy, no unload teardown) #36346

Closed as not planned

Description

@github-actions

🤖 AI-generated issue — filed automatically by the Daily Memory Leak Hunter gh-aw workflow (Pass A — runtime leak hunt). Every claim below was empirically proven by a standalone dotnet test against the shipped Microsoft.Maui.Controls NuGet package (no source build, no emulator). Please validate before acting.

Summary

Picker subscribes to its ItemsSource's INotifyCollectionChanged.CollectionChanged with a plain (strong) delegate and only unsubscribes when the ItemsSource property changes. When the bound collection out-lives the Picker — a shared/static/singleton ObservableCollection, or one on a view-model reused across navigations — and the page is torn down without ItemsSource being reassigned, the collection's CollectionChanged invocation list keeps the Picker alive. This is the #1 catalog pattern: shared publisher → strong CollectionChanged subscription, no teardown (focus area 4).

Why it retains

Picker.OnItemsSourceChanged(old, new) runs newObservable.CollectionChanged += CollectionChanged;. The matching -= runs only on the next ItemsSource change (oldObservable.CollectionChanged -= ...). There is no weak collection-changed proxy and no handler-disconnect teardown (the OnHandlerChanged override only drains pending open/close actions), so a long-lived collection holds a strong delegate whose Target is the Picker.

Retention path

ObservableCollection (long-lived: shared / static / singleton / reused VM)
  └─ CollectionChanged  (strong delegate)
       └─ Picker.CollectionChanged   ← delegate Target = the Picker
            └─ Picker  (+ Items, BindingContext, parent Element tree)

Source: src/Controls/src/Core/Picker/Picker.cs:314 (subscribe) — unsubscribe only at :309 (OnItemsSourceChanged(old, new), property-change path). OnHandlerChanged (:344) does not touch the subscription.

Repro (shipped package, plain net10.0, no device)

leakprobe.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <IsPackable>false</IsPackable>
    <LangVersion>latest</LangVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Maui.Controls" Version="10.0.0" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
    <PackageReference Include="xunit" Version="2.9.2" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
  </ItemGroup>
</Project>

LeakTest.cs:

using System;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Dispatching;
using Xunit;

namespace LeakProbe;

// Dispatcher stub so MAUI controls can be constructed on plain net10.0 (no platform).
static class TestInit
{
	[ModuleInitializer]
	public static void Init() => DispatcherProvider.SetCurrent(new StubDispatcherProvider());
}
sealed class StubDispatcherProvider : IDispatcherProvider
{
	readonly ThreadLocal<IDispatcher> _d = new(() => new StubDispatcher());
	public IDispatcher? GetForCurrentThread() => _d.Value;
}
sealed class StubDispatcher : IDispatcher
{
	public bool IsDispatchRequired => false;
	public bool Dispatch(Action action) { action(); return true; }
	public bool DispatchDelayed(TimeSpan delay, Action action) => true;
	public IDispatcherTimer CreateTimer() => new StubTimer();
}
sealed class StubTimer : IDispatcherTimer
{
	public TimeSpan Interval { get; set; }
	public bool IsRepeating { get; set; }
	public bool IsRunning => false;
	public event EventHandler? Tick;
	public void Start() { _ = Tick; }
	public void Stop() { }
}

public class PickerLeakTest
{
	const int N = 30;
	sealed class Payload : Picker { public readonly byte[] Data = new byte[1024 * 1024]; }

	static int CountAlive(WeakReference[] refs)
	{
		for (int i = 0; i < 8; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); }
		int alive = 0;
		foreach (var r in refs) if (r.IsAlive) alive++;
		return alive;
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	static WeakReference[] Control()
	{
		var refs = new WeakReference[N];
		for (int i = 0; i < N; i++) refs[i] = new WeakReference(new Payload());
		return refs;
	}
	[MethodImpl(MethodImplOptions.NoInlining)]
	static WeakReference[] Leaky(ObservableCollection<string> shared)
	{
		var refs = new WeakReference[N];
		for (int i = 0; i < N; i++) refs[i] = new WeakReference(new Payload { ItemsSource = shared });
		return refs;
	}
	[MethodImpl(MethodImplOptions.NoInlining)]
	static WeakReference[] Mitigation(ObservableCollection<string> shared)
	{
		var refs = new WeakReference[N];
		for (int i = 0; i < N; i++) { var v = new Payload { ItemsSource = shared }; v.ItemsSource = null; refs[i] = new WeakReference(v); }
		return refs;
	}

	[Fact]
	public void Picker_ItemsSource_Leaks()
	{
		var shared = new ObservableCollection<string> { "a", "b", "c" };
		int control = CountAlive(Control());
		int leaky = CountAlive(Leaky(shared));
		int mitigation = CountAlive(Mitigation(shared));
		GC.KeepAlive(shared);
		Assert.Equal(0, control);     // constructed Picker, no subscription -> collectable
		Assert.Equal(N, leaky);       // Picker subscribed to long-lived collection -> retained
		Assert.Equal(0, mitigation);  // clearing ItemsSource unsubscribes -> collectable
	}
}

Run:

cd leakprobe && dotnet test --logger "console;verbosity=normal"

Observed results

RESULT Picker_ItemsSource_Leaks: Control=0/30 alive (0 MB) | Leaky=30/30 alive (30 MB) | Mitigation=0/30 alive (0 MB)
Scenario Alive / N Retained
Control — constructed, never subscribed 0 / 30 0 MB
Leaky — subscribed to long-lived collection 30 / 30 ~30 MB
Mitigation — subscribe, then clear ItemsSource 0 / 30 0 MB

Leaky retaining all 30 while Control and Mitigation release proves the collection's strong CollectionChanged subscription is the sole root.

Affected platforms

All — pure managed cross-platform code in src/Controls/src/Core. No platform handler is needed to reproduce.

Condition: manifests when (a) ItemsSource is an INotifyCollectionChanged (e.g. ObservableCollection) and (b) that collection out-lives the Picker and the page is torn down without reassigning ItemsSource. A plain non-observable IList does not subscribe and does not leak.

Suggested fix

Subscribe to CollectionChanged through a weak collection-changed proxy (the repo already has weak-subscription building blocks such as src/Controls/src/Core/Internals/WeakEventProxy.cs, and BindableLayout demonstrates a weak CollectionChanged subscription) or unsubscribe from the collection when the handler disconnects (as the item-view controls do). Either removes the strong root while preserving live-update behavior.

Scope note (honest)

Partly a usage footgun (needs a collection that out-lives the Picker), but a genuine, easily-hit framework weakness: sharing one ObservableCollection across pages/tabs is common, and every such Picker then leaks its whole subtree. Aligning with the weak/handler-teardown pattern used elsewhere is the durable fix.

Generated by Daily Memory Leak Hunter · 2.3K AIC · ⌖ 287.2 AIC · ⊞ 49.9K · ◷

Activity

  1. added
    perf/memory-leak 💦
    on Jul 4, 2026
  2. added a commit that references this issue on Jul 22, 2026
    86183b6
  3. added 2 commits that reference this issue on Jul 28, 2026
    5c86fe0
    0add4d1
  4. kubaflo commented on Aug 14, 2026

    @kubaflo
    Contributor

    Closing this automated leak-scan issue as bot-generated tracker noise. The full report, links, labels, and comments have been archived so the underlying test, infrastructure, or workflow problem can still be investigated without keeping the product issue backlog open.

    Disclosure: this comment was generated by AI.

  5. locked and limited conversation to collaborators on Sep 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agentic-workflowsperf/memory-leak 💦

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions