Skip to content

Commit 800247f

Browse files
committed
fix(dependencyobject): Make shared value links to owners non-owning
A shareable DependencyObject used as a property value (brush, transform, projection, backdrop, ...) records the element it is applied to as its single associated parent with a strong reference, and the DataContext that element pushes into it stays applied after the value is replaced on the element. A long-lived shared value (style setter value, static brush) therefore retained the last element it was applied to and that element's DataContext, keeping whole pages alive after navigation. Hold the associated parent weakly, matching WinUI where the CMultiParentShareableDependencyObject parent association is non-owning, and clear the inherited DataContext when the only parent unassociates (WinUI: no mentor, bindings re-resolve against nothing). A collected parent still counts as a first parent, so the next consumer disables inheritance and drops the DataContext exactly as when the first parent is alive; the collectible-ALC sweep frees an expired slot the same way. Transform.Changed and Projection.Changed subscribers (the render transform adapter, Popup's arrange forwarding, UIElement's projection handler) now register weakly, so a transform or projection shared through a Style setter no longer roots every element ever styled with it. ToolTipService kept m_CurrentToolTip assigned after the automatic tooltip closed, rooting the tooltip and its owner until another tooltip opened; clear it when the service closes the current tooltip, as WinUI does in ToolTip::OnIsOpenChanged. Fixes unoplatform#25099
1 parent 462d020 commit 800247f

15 files changed

Lines changed: 683 additions & 99 deletions

File tree

‎src/Uno.UI.RuntimeTests/Tests/AssemblyLoadContext/Given_CollectibleAlcAssociations.cs‎

Lines changed: 92 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,21 @@ namespace Uno.UI.RuntimeTests.Tests.AssemblyLoadContext;
1515

1616
/// <summary>
1717
/// A shared (host-lifetime) resource consumed by a secondary-ALC element records that element as
18-
/// its InheritanceContext parent (<c>DependencyObjectStore._associatedParent</c>). Nothing
19-
/// un-associates it when the element's AssemblyLoadContext unloads, so the host resource pins the
20-
/// collectible ALC forever. These tests stage that association with an element whose type lives in
21-
/// a collectible (RunAndCollect) assembly and assert that
22-
/// <see cref="Application.CleanupNonDefaultAlcCaches"/> releases it.
18+
/// its InheritanceContext parent (<c>DependencyObjectStore._associatedParentRef</c>, a weak reference).
19+
/// Nothing resets it when the element's AssemblyLoadContext unloads. These tests stage that
20+
/// association with an element whose type lives in a collectible (RunAndCollect) assembly, keep the
21+
/// element alive across <see cref="Application.CleanupNonDefaultAlcCaches"/>, and assert that the
22+
/// sweep drops the stale association so the resource re-associates with its next live consumer (a
23+
/// stale parent would otherwise count as a second parent and disable inheritance for good). The
24+
/// association is observed directly: a ResourceDictionary item never inherits DataContext
25+
/// (<c>DependencyObjectStore.IsResourceDictionaryItem</c>), so bindings on it cannot reveal its parent.
2326
/// </summary>
2427
[TestClass]
2528
[RunsOnUIThread]
26-
// The association clearing runs identically on every Skia target, but the assertion depends on GC
27-
// reclaiming the now-unreferenced collectible element within a bounded GC.Collect() loop. The WASM
28-
// and UIKit (Mono) runtimes have non-deterministic/conservative GC and don't reliably reclaim it, so
29-
// the assertion is unreliable there. Coverage stays on CoreCLR-backed Skia (Desktop/Android) + WinAppSDK.
29+
// The sweep assertions run identically on every Skia target, but the trailing collection check depends
30+
// on GC reclaiming the released collectible element within a bounded GC.Collect() loop. The WASM and
31+
// UIKit (Mono) runtimes have non-deterministic/conservative GC and don't reliably reclaim it, so the
32+
// check is unreliable there. Coverage stays on CoreCLR-backed Skia (Desktop/Android) + WinAppSDK.
3033
[PlatformCondition(ConditionMode.Exclude, RuntimeTestPlatforms.SkiaWasm | RuntimeTestPlatforms.SkiaUIKit)]
3134
public class Given_CollectibleAlcAssociations
3235
{
@@ -48,65 +51,47 @@ public void Cleanup()
4851
}
4952

5053
[TestMethod]
51-
public void When_HostResourceAssociatedToCollectibleElement_Then_CleanupReleasesAssociation()
54+
public void When_HostResourceAssociatedToCollectibleElement_Then_CleanupClearsStaleAssociation()
5255
{
53-
var weakElement = StageHostResourceAssociation();
56+
var brush = new SolidColorBrush(Colors.Red);
57+
Application.Current.Resources[ProbeBrushKey] = brush;
58+
59+
var elementHolder = StageAssociation(brush);
5460

5561
// Explicit all-secondary sweep: this test exercises the global-teardown (unscoped) semantics.
5662
Application.CleanupAllSecondaryAlcCaches();
5763

58-
for (var i = 0; i < 10 && weakElement.IsAlive; i++)
59-
{
60-
GC.Collect();
61-
GC.WaitForPendingFinalizers();
62-
}
63-
64-
Assert.IsFalse(
65-
weakElement.IsAlive,
66-
"The host-lifetime brush's InheritanceContext association must be cleared during ALC " +
67-
"teardown cleanup; otherwise the brush pins the collectible element (and its entire " +
68-
"AssemblyLoadContext) for the host resource's lifetime.");
64+
AssertSweepClearedAssociation(brush, elementHolder);
6965
}
7066

7167
[TestMethod]
72-
public void When_ThemeDictionaryResourceAssociatedToCollectibleElement_Then_CleanupReleasesAssociation()
68+
public void When_CollectibleElementCollectedBeforeCleanup_Then_CleanupFreesExpiredAssociation()
7369
{
74-
var weakElement = StageThemeDictionaryAssociation();
70+
var brush = new SolidColorBrush(Colors.Green);
71+
Application.Current.Resources[ProbeBrushKey] = brush;
7572

76-
// Explicit all-secondary sweep: this test exercises the global-teardown (unscoped) semantics.
77-
Application.CleanupAllSecondaryAlcCaches();
73+
// The element is released and collected before the sweep runs, so the association has expired but its slot
74+
// is still taken: without the sweep freeing it, the next consumer would count as a second parent.
75+
var weakElement = ReleaseElement(StageAssociation(brush));
7876

7977
for (var i = 0; i < 10 && weakElement.IsAlive; i++)
8078
{
8179
GC.Collect();
8280
GC.WaitForPendingFinalizers();
8381
}
8482

85-
Assert.IsFalse(
86-
weakElement.IsAlive,
87-
"Associations recorded on resources inside (active) theme dictionaries must also be " +
88-
"cleared during ALC teardown cleanup.");
89-
}
90-
91-
// Staging happens in non-inlined frames so no test-method local keeps the element alive when
92-
// the collection assertion runs.
83+
Assert.IsFalse(weakElement.IsAlive, "Pre-condition: the collectible element must be collected before the sweep");
84+
Assert.IsNull(AssociatedParentOf(brush), "Pre-condition: the association must resolve to nothing once the element is collected");
9385

94-
[MethodImpl(MethodImplOptions.NoInlining)]
95-
private static WeakReference StageHostResourceAssociation()
96-
{
97-
var brush = new SolidColorBrush(Colors.Red);
98-
Application.Current.Resources[ProbeBrushKey] = brush;
99-
100-
var element = CreateCollectibleBorder();
101-
102-
// First consumption records the element as the brush's InheritanceContext parent.
103-
element.Background = brush;
86+
Application.CleanupAllSecondaryAlcCaches();
10487

105-
return new WeakReference(element);
88+
var consumer = new Border();
89+
consumer.Background = brush;
90+
Assert.AreSame(consumer, AssociatedParentOf(brush), "ALC teardown cleanup must free the slot of an already-collected parent so the resource re-associates with its next live consumer.");
10691
}
10792

108-
[MethodImpl(MethodImplOptions.NoInlining)]
109-
private WeakReference StageThemeDictionaryAssociation()
93+
[TestMethod]
94+
public void When_ThemeDictionaryResourceAssociatedToCollectibleElement_Then_CleanupClearsStaleAssociation()
11095
{
11196
var brush = new SolidColorBrush(Colors.Blue);
11297

@@ -125,12 +110,71 @@ private WeakReference StageThemeDictionaryAssociation()
125110
Assert.IsTrue(themed.TryGetValue(ProbeThemeBrushKey, out var resolved), "Pre-condition: the themed brush must resolve");
126111
Assert.AreSame(brush, resolved, "Pre-condition: resolution must yield the staged brush");
127112

113+
var elementHolder = StageAssociation(brush);
114+
115+
// Explicit all-secondary sweep: this test exercises the global-teardown (unscoped) semantics.
116+
Application.CleanupAllSecondaryAlcCaches();
117+
118+
AssertSweepClearedAssociation(brush, elementHolder);
119+
}
120+
121+
// Staging happens in non-inlined frames so no test-method local keeps the element alive once the
122+
// holder releases it; until then the holder keeps it alive across the sweep.
123+
124+
/// <summary>
125+
/// Makes the collectible element the brush's single InheritanceContext parent and returns a holder
126+
/// that keeps the element alive.
127+
/// </summary>
128+
[MethodImpl(MethodImplOptions.NoInlining)]
129+
private static object?[] StageAssociation(SolidColorBrush brush)
130+
{
128131
var element = CreateCollectibleBorder();
132+
133+
// First consumption records the element as the brush's InheritanceContext parent.
129134
element.Background = brush;
135+
Assert.AreSame(element, AssociatedParentOf(brush), "Pre-condition: the collectible element must be recorded as the resource's parent");
130136

131-
return new WeakReference(element);
137+
return new object?[] { element };
132138
}
133139

140+
private static void AssertSweepClearedAssociation(SolidColorBrush brush, object?[] elementHolder)
141+
{
142+
// The element is still alive, so only the sweep can have dropped the association.
143+
Assert.IsNull(AssociatedParentOf(brush), "ALC teardown cleanup must clear the resource's stale association with the collectible element.");
144+
145+
// With the stale association gone, the next live consumer is the resource's single parent again
146+
// instead of a second parent that would disable inheritance for good.
147+
var consumer = new Border();
148+
consumer.Background = brush;
149+
Assert.AreSame(consumer, AssociatedParentOf(brush), "After ALC teardown cleanup the resource must re-associate with its next live consumer.");
150+
151+
// Secondary check: once released, nothing retains the collectible element. The release happens in a
152+
// non-inlined frame so no temp of this frame keeps the element alive during the collection loop.
153+
var weakElement = ReleaseElement(elementHolder);
154+
155+
for (var i = 0; i < 10 && weakElement.IsAlive; i++)
156+
{
157+
GC.Collect();
158+
GC.WaitForPendingFinalizers();
159+
}
160+
161+
Assert.IsFalse(weakElement.IsAlive, "Nothing must retain the collectible element once it is released.");
162+
}
163+
164+
[MethodImpl(MethodImplOptions.NoInlining)]
165+
private static WeakReference ReleaseElement(object?[] elementHolder)
166+
{
167+
var weakElement = new WeakReference(elementHolder[0]);
168+
elementHolder[0] = null;
169+
return weakElement;
170+
}
171+
172+
/// <summary>
173+
/// The element the shared brush is associated with (<c>DependencyObjectStore.AssociatedParent</c>), or null.
174+
/// </summary>
175+
private static object? AssociatedParentOf(SolidColorBrush brush)
176+
=> ((IDependencyObjectStoreProvider)brush).Store.AssociatedParent;
177+
134178
/// <summary>
135179
/// Emits a <see cref="Border"/> subclass into a RunAndCollect (collectible) assembly — the
136180
/// same collectibility shape as an element type from an unloaded secondary app, without

‎src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_BindingMemoryLeak.cs‎

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ namespace Uno.UI.RuntimeTests.Tests.Windows_UI_Xaml
2121
#endif
2222
public class Given_BindingMemoryLeak
2323
{
24+
[TestCleanup]
25+
public void Cleanup()
26+
{
27+
// A failed test must not leave its tree rooted for retries and later tests.
28+
TestServices.WindowHelper.WindowContent = null;
29+
}
30+
2431
[TestMethod]
2532
public async Task When_xBind_View_Removed_Then_Collected()
2633
{
@@ -111,6 +118,49 @@ public async Task When_BrushSharedProgrammatically_Then_ViewModel_Collected()
111118
await AssertCollectedAsync(viewRef, vmRef);
112119
}
113120

121+
[TestMethod]
122+
[GitHubWorkItem("https://github.com/unoplatform/uno/issues/25099")]
123+
public async Task When_BrushShared_SingleOwner_Removed_Then_Owner_And_ViewModel_Collected()
124+
{
125+
// A long-lived brush (e.g. a static field) applied to one element at a time must not retain the
126+
// last element it was applied to.
127+
var sharedBrush = new SolidColorBrush(Colors.Red);
128+
129+
var root = new ContentControl();
130+
TestServices.WindowHelper.WindowContent = root;
131+
await TestServices.WindowHelper.WaitForIdle();
132+
133+
var (viewRef, vmRef) = CreateSingleOwnerSharedBrushView(root, sharedBrush);
134+
await TestServices.WindowHelper.WaitForLoaded((FrameworkElement)root.Content);
135+
136+
root.Content = null;
137+
138+
await WaitUntilCollectedAsync(viewRef);
139+
Assert.IsFalse(viewRef.IsAlive, "The element the shared brush was applied to should have been garbage collected after removal from visual tree.");
140+
141+
// The DataContext pushed into the brush is held at Inheritance precedence until the brush is re-associated:
142+
// the collected owner still counts as a first parent, so the next one disables inheritance and drops it.
143+
var next = new Border { Background = sharedBrush };
144+
await AssertCollectedAsync(viewRef, vmRef);
145+
146+
GC.KeepAlive(next);
147+
GC.KeepAlive(sharedBrush);
148+
}
149+
150+
[MethodImpl(MethodImplOptions.NoInlining)]
151+
private static (WeakReference viewRef, WeakReference vmRef) CreateSingleOwnerSharedBrushView(ContentControl root, Brush sharedBrush)
152+
{
153+
var vm = new BindingLeak_ViewModel { Text = "Single owner shared brush test" };
154+
155+
var owner = new Border { Background = sharedBrush, Width = 50, Height = 50 };
156+
var panel = new StackPanel { Width = 100, Height = 100, DataContext = vm };
157+
panel.Children.Add(owner);
158+
159+
root.Content = panel;
160+
161+
return (new WeakReference(owner), new WeakReference(vm));
162+
}
163+
114164
[MethodImpl(MethodImplOptions.NoInlining)]
115165
private static (WeakReference viewRef, WeakReference vmRef) CreateXBindView(ContentControl root)
116166
{
@@ -208,11 +258,19 @@ private static (WeakReference viewRef, WeakReference vmRef) CreateProgrammaticSh
208258
}
209259

210260
private static async Task AssertCollectedAsync(WeakReference viewRef, WeakReference vmRef)
261+
{
262+
await WaitUntilCollectedAsync(viewRef, vmRef);
263+
264+
Assert.IsFalse(viewRef.IsAlive, "View should have been garbage collected after removal from visual tree.");
265+
Assert.IsFalse(vmRef.IsAlive, "ViewModel should have been garbage collected after View removal from visual tree.");
266+
}
267+
268+
private static async Task WaitUntilCollectedAsync(params WeakReference[] references)
211269
{
212270
var sw = Stopwatch.StartNew();
213271
var timeout = TimeSpan.FromSeconds(10);
214272

215-
while (sw.Elapsed < timeout && (viewRef.IsAlive || vmRef.IsAlive))
273+
while (sw.Elapsed < timeout && Array.Exists(references, r => r.IsAlive))
216274
{
217275
GC.Collect(2);
218276
GC.WaitForPendingFinalizers();
@@ -234,9 +292,6 @@ private static async Task AssertCollectedAsync(WeakReference viewRef, WeakRefere
234292
// DispatcherConditionalDisposable to be executed
235293
await TestServices.WindowHelper.WaitForIdle();
236294
}
237-
238-
Assert.IsFalse(viewRef.IsAlive, "View should have been garbage collected after removal from visual tree.");
239-
Assert.IsFalse(vmRef.IsAlive, "ViewModel should have been garbage collected after View removal from visual tree.");
240295
}
241296
}
242297
}

0 commit comments

Comments
 (0)