Skip to content

fix(weakevents): Don't keep the first subscriber of a weak event alive - #25591

Merged
agneszitte merged 2 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/weak-event-first-subscriber
Oct 28, 2026
Merged

agneszitte merged 2 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/weak-event-first-subscriber

Conversation

@mikernet

Copy link
Copy Markdown
Contributor

GitHub Issue: closes #25590

PR Type:

🐞 Bugfix

What changed? 🚀

WeakEventCollection.Register passed its trim callback as _ => Trim(). The compiler put that lambda on the same closure class as the RemoveRegistration local function, which holds the subscriber's own delegate (actualTarget). Gen2GcCallback keeps its callback strongly referenced and re-registers itself on every gen 2 GC while the collection has a live registration. So the subscriber that registered on an empty collection stayed in memory for as long as the event source lived and anything else was subscribed to it, unless its registration was disposed.

With Brush.RegisterInvalidateRender, a long-lived theme brush kept the first TextBlock that used it alive, along with its whole page. In a WebAssembly app, five such callbacks held 108 MB of a 282 MB managed heap: three pages the user had already left (see the issue for the heap dump chain).

Short weak references to an object held this way are cleared, even though the callback's finalizer keeps resurrecting it, so leak tests built on new WeakReference(obj) don't see it. The new tests use a resurrection-tracking reference where they go through the real Gen2GcCallback.

  • The fix: the trim callback is now a static lambda that gets the collection from the target Gen2GcCallback passes back, so it captures nothing.
  • A second, smaller fix: a collection used to register another trim callback each time it went from empty to one registration. Earlier callbacks only stopped when they ran and found the collection empty, so emptying and re-subscribing between two gen 2 GCs left several running. The collection now tracks, under its lock, whether its callback is still running, and only registers a new one after the previous one has stopped. This is a separate perf commit.

Tests

New tests in Given_WeakEventHelper:

  • When_First_Subscriber_Not_Referenced_Then_Collected: uses the existing TestPlatformProvider, which keeps the trim callback strongly referenced as Gen2GcCallback does. A first subscriber that owns its undisposed registration, as Brush.SetupBrushChanged callers do, is collected while a second one stays subscribed.
  • ..._With_Default_Trim_Provider: the same scenario with the real Gen2GcCallback, checked through a WeakReference with trackResurrection: true.
  • When_Registered_Again_Before_Trim_Then_Single_Trim_Callback and When_Registered_After_Trim_Stopped_Then_Trim_Callback_Registered: check the single-callback behaviour, using a provider that simulates Gen2GcCallback.

Results on Skia desktop:

  • On master: both leak tests fail, and the single-callback test fails with Expected:<1>. Actual:<2>.
  • With only the fix commit: the leak tests pass, and the single-callback test still fails.
  • With both commits: all 12 tests in Given_WeakEventHelper pass.
  • Stability: both leak tests passed 50 runs in a row.

Related classes, run with three attempts:

  • Classes: Given_SolidColorBrush_UITest, Given_GradientBrush, Given_BindingMemoryLeak, Given_FrameworkElement_And_Leak, Given_ProgressRing, Given_HighContrastAdjustment, Given_RichTextBlock.When_Foreground_Changed_Dynamically and Given_ElementTheme.
  • Result: 254 of 255 pass. The exception is Given_ProgressRing.When_Stretch_Fill (Expected:<100,50>. Actual:<100,50.4>), which fails the same way on master on this machine because of display scaling.

The other RegisterTrimCallback users were checked as well. DefaultArrayPool and LinearArrayPool already pass non-capturing lambdas. LRUCache captures only the cache that owns the target, so it outlives the cache by one gen 2 GC at most.

PR Checklist ✅

WeakEventCollection.Register passed its trim callback as a lambda that
the compiler put on the same closure class as the RemoveRegistration
local function, which holds the subscriber's delegate. Gen2GcCallback
keeps that callback strongly referenced and re-registers itself on
every gen 2 GC while the collection has a live registration. So the
subscriber that registered on an empty collection stayed in memory as
long as the event source lived and anything else was subscribed,
unless its registration was disposed.

With Brush.RegisterInvalidateRender, a long-lived theme brush kept the
first TextBlock that used it alive, along with its whole page. Short
weak references to such an object are cleared even though the
callback's finalizer keeps it in memory, which hid the leak from
tests.

The trim callback is now a static lambda that gets the collection from
the target Gen2GcCallback passes back, so it captures nothing.

Fixes unoplatform#25590
A collection registered a trim callback each time it went from empty
to one registration. A callback only stops when it runs and finds the
collection empty, so when the collection was emptied and subscribed to
again before the next gen 2 GC, the earlier callback kept running next
to the new one, and more piled up with each such cycle.

The collection now tracks under its lock whether its callback is still
running, and only registers a new one once the previous one stopped.
Copilot AI balanced review requested due to automatic review settings October 20, 2026 10:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The focused changes preserve lifecycle synchronization and include targeted regression coverage, with no unresolved findings.

No open issues 🎉

What changed in this PR

Fixes #25590 by preventing weak-event trim callbacks from retaining the first subscriber.

Changes:

  • Uses a non-capturing static trim callback.
  • Tracks callback registration to prevent duplicate active callbacks.
  • Adds regression tests for subscriber collection and callback lifecycle.
File Description
src/​Uno.WinRT/​UI/​Core/​WeakEventHelper.cs Removes subscriber capture and prevents duplicate trim callbacks.
src/​Uno.UI.RuntimeTests/​Windows/​UI/​Given_WeakEventHelper.cs Tests collection with simulated and default providers, plus callback restart behavior.

Review effort: Balanced

mikernet added a commit to Singulink/uno that referenced this pull request Oct 20, 2026
…e (port)

Port of the first commit of unoplatform#25591 (2f9213f), for
unoplatform#25590.

WeakEventCollection.Register passed its trim callback as a lambda that
the compiler put on the closure of the RemoveRegistration local
function, which holds the subscriber's delegate. Gen2GcCallback keeps
that callback alive and re-registers itself on every gen 2 GC while
the collection has a live registration, so the first subscriber of a
weak event stayed in memory as long as the source lived and anything
else was subscribed. In DropDoc's WebAssembly app, theme brushes kept
the first TextBlocks that used them alive with their pages (108 MB).
The trim callback is now a static lambda that captures nothing.

- Tests: Given_WeakEventHelper.When_First_Subscriber_Not_Referenced_Then_Collected
  and its variant with the real Gen2GcCallback.
mikernet added a commit to Singulink/uno that referenced this pull request Oct 20, 2026
Port of the second commit of unoplatform#25591 (ab2bf54).

A collection registered another trim callback each time it went from
empty to one registration, and the earlier ones kept running while it
had registrations. It now only registers a new one once the previous
one stopped.
@mikernet

Copy link
Copy Markdown
Contributor Author

Could this be backported to servicing/6.8 once it's merged? WeakEventHelper.WeakEventCollection.Register is the same in 6.8 (src/Uno.UWP/UI/Core/WeakEventHelper.cs at 5efcb98). On 6.8 this leak kept three departed pages alive in our WebAssembly app through theme brushes. Both commits and their tests apply to 6.8 with only the path change. We've been running them on a 6.8 build: all 12 Given_WeakEventHelper tests pass, and the three new ones fail without the fixes.

@agneszitte

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 1 pipeline(s).

@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 240474 found UI Test snapshots differences: skia-linux-screenshots: 118, skia-windows-screenshots: 2458

Details
  • skia-linux-screenshots: 118 changed over 2458

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • CalendarView_Theming.png-dark
    • Buttons.png
    • CalendarView_Theming.png
    • ClipboardTests.png-dark
    • CompositionEffectBrush.png-dark
    • CompositionEffectBrush.png
    • CompositionNineGridBrush_Source_Changes.png-dark
    • CompositionNineGridBrush_Source_Changes.png
    • DisplayInformation.png-dark
    • DoubleImageBrushInList.png-dark
    • DoubleImageBrushInList.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • DynamicFont.png-dark
    • DynamicFont.png
    • Gamepad_CurrentReading.png-dark
    • Gamepad_Enumeration.png-dark
  • skia-windows-screenshots: 2458 changed over 2488

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_ScreenReader.png
    • AppBarButtonWithIconTest.png-dark
    • ApplicationViewMode.png-dark
    • AppWindowClosing.png-dark
    • AppWindowPresenters.png-dark
    • ArcSegment.png
    • Attributed_text_Supserscript.png-dark
    • AuthenticationBroker_Demo.png
    • AutoBorderStretchwithtopmargin.png
    • AutomationPropertiesExtensions_Role.png-dark
    • AutoSuggestBox_BitmapIcon.png-dark
    • AutoSuggestBox_BitmapIcon.png
    • BackGesture.png-dark
    • BackGesture.png
    • Basics.png-dark
    • Basics.png
    • BezierSegment.png-dark
    • BezierSegment.png
    • BitmapIcon_Monochromatic.png-dark
    • BitmapIcon_Monochromatic.png

@mergify

mergify Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@agneszitte
agneszitte merged commit 4997dfa into unoplatform:master Oct 28, 2026
46 checks passed
agneszitte added a commit that referenced this pull request Oct 28, 2026
…bscriber-6.8

fix(weakevents): Don't keep the first subscriber of a weak event alive (backport #25591)
agneszitte added a commit that referenced this pull request Nov 3, 2026
…6.7/pr-25730

fix(weakevents): Don't keep the first subscriber of a weak event alive (backport #25591) (backport #25730)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

6 participants