Skip to content

WeakEventHelper keeps the first subscriber of each weak event alive for as long as the event source lives #25590

Closed

Description

@mikernet

Current behavior

WeakEventHelper.WeakEventCollection keeps the first subscriber of each weak event alive, strongly, for as long as the event's source lives.

Register registers a trim callback when the first handler is added:

internal IDisposable Register(WeakReference target, GenericEventHandler handler, Delegate actualTarget)
{
	lock (_lock)
	{
		WeakHandler key = new(target, handler);
		_handlers.Add(key);

		if (_handlers.Count == 1)
		{
			_provider.RegisterTrimCallback(_ => Trim(), this);
		}

		return Disposable.Create(RemoveRegistration);

		void RemoveRegistration()
		{
			actualTarget = null!;
			...
		}
	}
}

The lambda only calls Trim(), but the compiler emits it on the method's closure class. RemoveRegistration captures actualTarget and this, so that closure class holds both, and the lambda ends up on it too. In the shipped Uno.dll (uno.winrt 6.8.0-dev.222) the Func<object, bool> is created with <>c__DisplayClass10_0 as its target, and that class has the actualTarget and <>4__this fields. Master has the same code (src/Uno.WinRT/UI/Core/WeakEventHelper.cs).

Gen2GcCallback holds that delegate strongly. It resurrects itself after every gen 2 collection while its weak target (the collection) is alive and Trim() returns true, that is, while the collection has any live registration. So the delegate that registered when the collection was empty stays reachable for as long as the source lives and something else is subscribed to it. Its target stays reachable too, and so does everything that target references, unless that particular registration is disposed. That is the opposite of what RegisterEvent promises ("both the source and the target are weak").

The most visible case is Brush.RegisterInvalidateRender. The source is a brush, a theme or resource brush lives for the life of the app, and other elements keep subscribing to it. Whichever element first registered for render invalidation on that brush stays alive with its whole visual tree and its DataContext, after its page has been navigated away from. That is one element per brush, but an app uses many brushes, so the pinned pages add up.

This leak is easy to miss. Gen2GcCallback is reachable only through the finalization queue, so ordinary (short) weak references to what it holds are cleared, even though the objects stay in memory, resurrected with the callback on every collection. A leak test or a diagnostic that uses new WeakReference(obj) reports the subscriber as collected. Only a WeakReference with trackResurrection: true, or a heap dump, shows it.

Separately, each time a collection goes from no registrations to one, another callback is registered, and the earlier ones keep running for as long as the collection has registrations.

Measured in a WebAssembly app (Skia renderer) with a GC heap dump (collectGcDump(), .NET 10) after browsing a few admin pages that each show several DataGrids. The managed heap was 282 MB, against 23 MB at startup. Rebuilding reachability with the weak table keys taken into account showed 108.5 MB reachable only through objects waiting for finalization: five Windows.Foundation.Gen2GcCallback instances, each with this chain:

Gen2GcCallback
  -> Func<object, bool>
    -> WeakEventHelper.WeakEventCollection.<>c__DisplayClass10_0
      -> Action (actualTarget)
        -> TextBlock
          -> DependencyObjectStore -> DataContext -> page view model -> ... -> the page and its whole tree

The owners of the five collections were SolidColorBrush instances, and the captured subscribers were TextBlock and ImplicitTextBlock render invalidation handlers. Together they held three departed pages, about 50 MB each because of their DataGrids, plus two other page view models. On WebAssembly this drives the app to the 2 GB limit.

Expected behavior

A subscriber registered through WeakEventHelper.RegisterEvent is collectable once nothing else references it, whatever the order of registration. The trim callback should only need the collection, which Gen2GcCallback already passes back as its target:

_provider.RegisterTrimCallback(static target => ((WeakEventCollection)target).Trim(), this);

How to reproduce

  1. Create a WeakEventCollection and keep it alive, as a long-lived brush would.
  2. Register a handler whose target is an object referenced nowhere else (subscriber A). Keep the returned disposable without disposing it, as Brush.SetupBrushChanged callers do.
  3. Register a second handler from a subscriber that stays alive (subscriber B), as the elements on the current page would.
  4. Drop subscriber A, keeping a WeakReference to it created with trackResurrection: true. Collect and wait for pending finalizers a few times.
  5. Subscriber A is still alive. Register them the other way round, B first and then A, and A is collected.

Environment

  • Uno.WinUI 6.8.0-dev.222 (Uno.Sdk 6.8.0-dev.66). The same code is on master at 55cddbc.
  • .NET 10, runtime pack 10.0.12.
  • Heads: net10.0-browserwasm (Skia renderer), where it reaches the 2 GB limit. The lifetime is the same on every head that uses WeakEventHelper.

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