Repository navigation
Remove DO finalizers - #23703
Remove DO finalizers#23703
Conversation
7ea26d1 to
0ec29c3
Compare
|
Claude finished @MartinZikmund's task in 10m 3s —— View job PR Review —
|
| Severity | Count | Type |
|---|---|---|
| Low | 2 | Stale/misleading comments |
Finding 1 — Stale header comment in DependencyObject.mux.cs (inline comment posted)
Lines 5–8 still say "in Uno, DependencyObject is an interface on every target, so the CDependencyObject layer lives on the DependencyObject that every DependencyObject owns". This was true before this PR but is now factually wrong — DependencyObject is a concrete base class carrying the store directly.
Finding 2 — BinderDispose() dead code + stale finalizer comment (inline comments posted)
BinderDispose() is unreferenced (the finalizer that called it was intentionally removed in commit a7ed2b99). The method's inner comment "may be invoked from both a finalizer and the dispatcher" is now misleading. The _gate lock field has no other use. Prefer removing both rather than keeping them with a stale comment.
Cross-cutting observations (no blocking issues)
IsStoreInitialized => true: now always-true public property with zero callers inside the repo. Safe for binary compat but effectively dead. Could be[EditorBrowsable(Never)]or removed in a subsequent cleanup.ActualInstance => this: identity alias kept for internal API consistency during the migration — acceptable for now, can be eliminated once all callers are updated.Windows.ApplicationModel.Callsimport inDependencyObject.Store.cs: present in the originalDependencyObjectStore.cstoo; appears unused in this file. Pre-existing, out of scope for this PR.#if UNO_HAS_ENHANCED_LIFECYCLE ... newguards onProgressRing.IsActive,StateTrigger.IsActive,FlyoutBase.Enter/Leave,KeyboardAccelerator*: correctly hides the baseDependencyObjectmethods that only exist under that flag. Guarding thenewkeyword is the right approach.DependencyPropertyDetailsCollectionstrong owner ref: the reasoning in the comment is sound (DO↔collection cycle is transparent to the tracing GC; avoids renting a pooledManagedGCHandleper object). The now-emptyTryEnableHardReferences/DisableHardReferencesare correct no-ops.
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23703/wasm-skia-net9/index.html |
|
The build 221477 found UI Test snapshots differences: Details
|
|
|
0ec29c3 to
de487b5
Compare
|
Claude finished @MartinZikmund's task in 7m 3s —— View job PR Review —
|
| Severity | Count | Type |
|---|---|---|
| Low | 4 | Stale comments / dead code |
Finding 1 — Stale header comment in DependencyObject.mux.cs (inline posted)
Lines 5–8 still say "in Uno, DependencyObject is an interface on every target, so the CDependencyObject layer lives on the DependencyObject that every DependencyObject owns (operating on ActualInstance)". This was accurate before this PR but is now factually wrong — DependencyObject is a concrete base class that carries the store directly.
Finding 2 — BinderDispose() dead code + stale inner comment (inline posted on _gate field, line 36)
The finalizer that called BinderDispose() was intentionally removed in commit e4debc20. BinderDispose() is now unreferenced dead code; _gate has no other user. The Store.cs comment at line 241–244 documents that this is deliberate (for structural parity with the base branch), but the inner comment "Guard the dispose as it may be invoked from both a finalizer and the dispatcher" is stale and should be updated.
Finding 3 — IsDisposed guards are now permanently dead (inlines posted on EventManager.uno.cs:74 and CustomEventManager.cs:77)
DependencyObject._isDisposed is only ever set inside BinderDispose(). Since BinderDispose() is now unreachable, IsDisposed always returns false. The IsDisposed guards in EventManager.RaiseLayoutUpdated() and CustomEventManager.OnTick() — along with their "via finalizer" comments — are permanent no-ops and should be removed to prevent future confusion.
Finding 4 — Unused using Windows.ApplicationModel.Calls; in DependencyObject.Store.cs (line 19)
Pre-existing unused import, carried over from the DependencyObjectStore.cs rename. Safe to remove. (Inline comment could not be placed on this file due to GitHub's pure-add diff restrictions.)
Cross-cutting observations (no blocking issues)
IsStoreInitialized => true: always-true public property kept for binary compatibility — zero callers in-repo. The previous review noted this; acceptable for now, candidate for[EditorBrowsable(Never)]in a follow-up.ActualInstance => this: identity alias maintained for migration purposes. Fine; can be inlined away once all call-sites are updated.DependencyPropertyDetailsCollectionstrong owner ref: the reasoning (DO↔collection cycle transparent to tracing GC) is sound, and the now-emptyTryEnableHardReferences/DisableHardReferencesare correct no-ops.AttachedDependencyObject: base(owner)fix: correct — now the store's_originalObjectTyperesolves to the wrapped POCO's type, matching the pre-existing intent.#if UNO_HAS_ENHANCED_LIFECYCLEguards onnewkeyword (ProgressRing.IsActive,StateTrigger.IsActive,FlyoutBase.Enter/Leave,KeyboardAccelerator*): guardingnewunder the flag that gates the base method is the right approach.FrameworkElement.Parentvia((DependencyObject)this).Parent: resolves statically toDependencyObject'sinternal object?property (not recursive), as expected.
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23703/wasm-skia-net9/index.html |
|
The build 222008 found UI Test snapshots differences: Details
|
Review threads triaged (7 unresolved)No new commit was pushed this run. All seven open threads are already satisfied by the current branch HEAD Already fixed by
|
| file:line | reviewer point | state on HEAD |
|---|---|---|
src/Uno.UI/UI/Xaml/DependencyObject.mux.cs (header) |
Header still said "in Uno, DependencyObject is an interface on every target … the store the DO owns" |
Rewritten to "…DependencyObject is the concrete base class that directly carries the property store, so the CDependencyObject layer lives on it (ActualInstance is an identity alias returning this)" — matches the wording the reviewer proposed. (Two threads, both already marked outdated.) |
src/Uno.UI/UI/Xaml/DependencyObject.Binder.cs:229 |
Inner comment "may be invoked from both a finalizer and the dispatcher" is stale | Now reads "Guard the dispose against concurrent invocation."; a note above BinderDispose() states it is currently unreferenced and why it is kept. |
No change needed — deliberate, and documented in code (4)
| file:line | reviewer point | why the code is left as-is |
|---|---|---|
DependencyObject.Binder.cs:227 / DependencyObject.Store.cs:244 |
Delete BinderDispose() (dead code) |
Intentionally kept so that removing the finalizer stays the only behavioral diff vs. the base branch — that is the whole point of a perf experiment commit (perf(experiment): Drop the DependencyObject finalizer). The rationale and the promotion plan are written down in the EXPERIMENT note in DependencyObject.Store.cs:241-247: "if this experiment is promoted, drop BinderDispose, _gate, IsDisposed and its guards together." Deleting them now would bundle an unrelated cleanup into the measurement. |
DependencyObject.Binder.cs:36 |
_gate is unused |
Same rationale — it is read by BinderDispose(), so it is neither an unused-field warning nor an accident. The stale part of that thread (the finalizer wording) was fixed. |
Internal/EventManager.uno.cs:75 |
IsDisposed guard is a permanent no-op; remove it |
Correct analysis, and it is now stated verbatim at the call site ("Inert while the DO finalizer is removed — nothing sets IsDisposed"). Kept for the same revert-cleanliness reason as above. I confirmed by inspection that EventManager and CustomEventManager are the only consumers of DependencyObject.IsDisposed (the other IsDisposed hits in the tree are ManagedWeakReference / InputCursor), so the note is accurate and nothing else silently changed behavior. |
Internal/CustomEventManager.cs:78 |
Same guard, same no-op | Same as above. |
Needs @MartinZikmund input (0)
None — the keep-vs-delete decision is already recorded in the code with an explicit promotion checklist. Worth a conscious call before this leaves draft: if the experiment is being promoted rather than measured, BinderDispose() + _gate + IsDisposed + its two guards should go in one follow-up commit, exactly as the note says.
Validation level: code inspection only — nothing was built, run, or tested in this pass, and no new code was produced to validate. Azure Pipelines CI on 50624743aa is the source of truth.
5062474 to
d9cbf82
Compare
|
Claude finished @MartinZikmund's task in 7m 47s —— View job PR Review —
|
| Severity | Count | Type |
|---|---|---|
| Low | 1 | Stale class name in EXPERIMENT comment (inline posted) |
| Lint | 1 | Unused using (pre-existing, cannot post inline on unchanged line) |
Finding 1 — Stale "CustomEventManager" in EXPERIMENT note (inline posted, DependencyObject.Store.cs:246)
The EXPERIMENT note says "its callers (EventManager/CustomEventManager) are inert." A codebase-wide search finds no CustomEventManager class — the only DependencyObject.IsDisposed consumer is EventManager.uno.cs:74. The name should be removed or corrected.
Finding 2 — using Windows.ApplicationModel.Calls; is unused (DependencyObject.Store.cs:19)
Carried over from the DependencyObjectStore.cs rename; no type from that namespace is used in this file. Flagged in the round-2 review as out-of-scope. Still present — a trivial removal candidate when convenient. (Cannot post an inline on this line as it is unchanged in the PR's effective diff.)
Prior findings resolved
| Finding | Commit |
|---|---|
Stale interface-era header in DependencyObject.mux.cs |
d9cbf822 |
BinderDispose() inner comment "may be invoked from both a finalizer" |
d9cbf822 |
EventManager.uno.cs — stale "via finalizer" comment |
d9cbf822 |
Intentionally kept (per EXPERIMENT note in DependencyObject.Store.cs:241-247)
BinderDispose(), _gate, _isDisposed, and the IsDisposed guard in EventManager.uno.cs are kept unreferenced so that removing the finalizer is the only behavioral diff vs. the base branch. The promotion checklist is documented inline.
Cross-cutting observations (no blocking issues)
DependencyPropertyDetailsCollectionstrong owner ref: correct — DO↔collection cycle is transparent to the tracing GC;TryEnableHardReferences/DisableHardReferencesare correct no-ops.FrameworkElement.Parent newshadowing:((DependencyObject)this).Parentresolves statically toDependencyObject.internal object? Parent(not the hidingFrameworkElement.public new DependencyObject Parent) — no infinite recursion.GetTemplatedParent2()/SetTemplatedParent2()guards:ENABLE_LEGACY_TEMPLATED_PARENT_SUPPORTis always defined inUno.UI.csproj, so the unguarded calls inFrameworkElement.GetTemplatedParent()/SetTemplatedParent()are safe. Pattern is pre-existing.PackageDiffIgnore.xmlentries: correctly suppress binary-compat false-positives for the removedDependencyObjectStoreandIDependencyObjectStoreProvider.IsStoreInitialized => true: always-true, zero in-repo callers, kept for binary compat.ActualInstance => this: identity alias, acceptable for migration period.
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23703/wasm-skia-net9/index.html |
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-23703/docs/index.html |
|
The build 226939 found UI Test snapshots differences: Details
|
d9cbf82 to
9b7c98d
Compare
|
Claude finished @MartinZikmund's task in 3m 20s —— View job PR Review —
|
| Severity | Count | Type |
|---|---|---|
| Low | 2 | Stale / inconsistent comments |
Finding 1 — Timeline.cs:428-430 — Stale comment before ~Timeline() (inline posted)
The comment explains why GC.SuppressFinalize(this) was replaced with _disposed = true: "it would also skip the inherited ~DependencyObject, leaving the binder state and its pooled references unreleased." That rationale was accurate in commit 4d201ee5 (when it was written), but commit 764633bc subsequently removed DependencyObject's finalizer entirely. The _disposed guard is still functionally correct (it skips the redundant async Dispose(false) dispatch), but the explanation is now wrong on this branch.
Finding 2 — DependencyObject.Store.cs:246 — Stale CustomEventManager name (inline posted, third appearance)
The EXPERIMENT note says (EventManager/CustomEventManager) are inert. A repo-wide search confirms no class named CustomEventManager exists; only EventManager.uno.cs reads IsDisposed. Flagged in rounds 2 and 3; still unaddressed.
Intentionally kept (per EXPERIMENT note in DependencyObject.Store.cs:241-247)
BinderDispose(), _gate, _isDisposed, and the IsDisposed guard in EventManager.uno.cs are kept unreferenced so that removing the finalizer is the only behavioral diff vs. the base branch. The promotion checklist is documented inline.
Pre-existing lint
using Windows.ApplicationModel.Calls; in DependencyObject.Store.cs:19 is unused. Carried over from the rename; cannot post inline on an unchanged line. Safe to remove when convenient.
Validation level: code inspection only — no local build or runtime test run.
Three sites dereferenced SelfWeakReference.Target purely to get the current instance, which is what `this` already is - the reference is a self weak reference, so Target can never be anything else while an instance method is running. This mattered because the property-store validation path is one of them: ValidatePropertyOwner runs on every GetValue/SetValue when ValidatePropertyOwnerOnReadWrite is on, which is the default in DEBUG and whenever a debugger is attached. Minting the handle there defeated the whole point of making SelfWeakReference lazy - every DO rented a pooled ManagedGCHandle on first property access in exactly the configurations developers run. The benchmark only ever measured Release without a debugger, which is the one configuration where the laziness held. The other two are the SetValue debug log, which now reads the name and hash code directly off the instance. No SelfWeakReference.Target uses remain. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RrLpnAZeR1wBYdzwcqTPtP
InvokeCallbacks is the inner loop of every property change. Making SelfWeakReference lazy moved it from a hoisted local to a property access evaluated once per child store and once per generic callback - a null check plus a property dispatch per iteration, which on the Mono interpreter is a full dispatch rather than an inlined field read. Hoist it back into a local, but inside a count guard so the laziness is preserved: an object with no inheriting children and no generic callbacks still never rents a weak self-handle. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RrLpnAZeR1wBYdzwcqTPtP
SelfWeakReference used to be forced non-null by the constructor, which ran on the constructing thread. Making it lazy moved the first mint onto the property-change path, where a bare `??=` can let two threads each rent a handle and publish a different one. That matters because the handle is an identity, not just a value: consumers cache it (the inherited-forwarded-property map, parent-changed callbacks) and a second identity for the same object diverges from the cached one. The loser also cannot be returned to the pool, because WeakReferencePool.ReturnWeakReference refuses self references - it is freed only by ManagedGCHandle's finalizer. Interlocked.CompareExchange makes the publication single-winner. It runs once per object and only while the field is null, so it costs nothing on the steady-state path. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RrLpnAZeR1wBYdzwcqTPtP
The owner field was widened to `object` when it stopped being a ManagedWeakReference, and `Owner` kept a nullable return it can no longer produce. Both understate the new contract: the only legal argument is the owning DependencyObject, and it is always present. This is not cosmetic. The safety argument for holding the owner strongly is entirely "the collection never escapes its DependencyObject" - an `object` parameter lets a future caller pass something else and turn that into an unbounded pin with no compile-time signal. Type it, and state the invariant on the field so the next reader has to work to break it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RrLpnAZeR1wBYdzwcqTPtP
Holding the owner strongly left DependencyPropertyDetailsCollection's TryEnableHardReferences/DisableHardReferences as empty methods that the store still called on every load and unload. Delete them and the two call sites. Worth recording why this is safe rather than merely tidy: the reference those toggles governed was `_hardOwnerReference = _ownerReference.Target` - the owning DependencyObject itself. That was always a self-edge inside the DO <-> collection cycle, so clearing it on unload released nothing that the cycle did not already release. Making it permanent is leak-neutral, which is why no leak test moved. IsStoreHardReferenceEnabled now governs only the parent reference, so its documentation says that instead of the general "some highly used fields". An operator flipping it off to bisect a retention problem should get an accurate description of what it turns off. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RrLpnAZeR1wBYdzwcqTPtP
The details collection holds its owning DependencyObject strongly, so the two form a reference cycle. That is safe only because the collection never escapes its owner - the cycle is then unreachable as a unit and the tracing GC reclaims it whole. Nothing enforced that; the safety argument lived only in a comment. This test populates the store and gives the owner an inheriting child (so it also mints the pooled self weak reference), drops both, and asserts they are collected. If anyone later hands the collection, or a closure capturing it, to a longer-lived structure, the owner stops being collectable and this fails. Validated by negative control: inverting the owner assertion makes the test fail with `ownerWR.Target` non-null, confirming the test executes and that the object is genuinely collected rather than the assertion being vacuous. Restored, the suite is 4021 tests / 12 failed - the same pre-existing When_Calendar timezone failures as before, 0 regressions. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01RrLpnAZeR1wBYdzwcqTPtP
SelfWeakReference publishes through Interlocked.CompareExchange, so a second thread racing the first mint always loses. The loser's handle was simply dropped: WeakReferencePool.ReturnWeakReference refuses self references by design, so nothing recycled it and its native GCHandle survived until ManagedGCHandle's finalizer ran. That is precisely the finalization churn this branch exists to remove, so free it on the spot instead. The minted reference never escaped - CompareExchange failing means it was never stored - so disposing it is observationally invisible. The fast path also stops re-reading the field: it is loaded once into a local and returned, rather than being read for the null test and again for the return. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01GP2BeVCQzY3sQB7QBv173u
f8596ed to
0531487
Compare
|
Claude encountered an error after 0s —— View job I'll analyze this and get back to you. |
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23703/wasm-skia-net9/index.html |
|
The build 230985 found UI Test snapshots differences: Details
|
|
Tick the box to add this pull request to the merge queue (same as
|
ActualInstance has been `=> this` since the property store merged into
DependencyObject, so it can never be null. Dropping the nullable
annotation removes the dead null handling it kept alive: the
`else { Parent = null; }` fallback in InnerSetValue - the last
"store lost its instance" path left in the tree - two `!` suppressions,
and two guard blocks in CleanupInheritedProperties and OnParentChanged.
Picks up the part of #17827 that survives the store merge. The rest of
that PR - the strong self reference itself - already landed on this
branch in a form that keeps the parent hard-reference support intact.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01NEgUoa8er27B2zx2VQyP5w
|
Claude encountered an error after 0s —— View job I'll analyze this and get back to you. |
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23703/wasm-skia-net9/index.html |
|
The build 231118 found UI Test snapshots differences: Details
|
_entryOffsets is indexed by bucketIndex alone, so it needs bucketIndex + 1 slots, but it rented (bucketIndex * BucketSize) + 1 - a 16x over-allocation. Because bucketIndex derives from DependencyProperty.UniqueId, a process-wide counter, the waste scales with the highest property id an object touches: with ~2000 properties registered in Uno.UI alone, a DependencyObject that sets a late-registered property carried a 4 KB short[] where 256 bytes suffice. The multiplier bought nothing. ArrayPool rounds a request up to a power-of-two bucket, so growth stays geometric and resizes stay amortized O(1); the total allocated across resizes is now ~2x the final size rather than one 16x slab. The oversized InitBlockUnaligned fill shrinks with it. Measured at bucket index 17: 512 slots rented for 18 needed, now 32. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016yv4DH5RYAoVM8GjEWtXDS
Fails before the previous commit with 512 slots rented for a bucket index of 17, where 18 are needed. The two growth tests walk the offsets array up and down and read back every bucket it claims to cover, so a future resizing change cannot trade addressability for the smaller rental. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016yv4DH5RYAoVM8GjEWtXDS
|
Claude encountered an error after 0s —— View job I'll analyze this and get back to you. |
|
The build 231216 found UI Test snapshots differences: Details
|
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23703/wasm-skia-net9/index.html |
|
The build 231698 found UI Test snapshots differences: Details
|
GitHub Issue: Part of #8339 — also advances unoplatform/uno-private#2055 (
DependencyObjectshould be a class [7.0], BC26).PR Type:
🔄 Refactoring (no functional changes, no api changes) — internal lifetime/GC semantics only
What changed? 🚀
#23702 left every
DependencyObjectfinalizable and renting a pooled weak self-handle. This PR takes both off the table, soDependencyObject— the most-instantiated type in the framework — no longer participates in finalization at all.1.
~DependencyObjectis removed. The finalizer was not load-bearing: it only calledBinderDispose, whose entire payload was returning pooled weak references and arrays. It unrooted nothing. Native weak handles are freed byManagedGCHandle's own finalizer, which remains.2. The per-DO weak self-handle is dropped.
DependencyPropertyDetailsCollectionnow holds its owningDependencyObjectstrongly instead of through a rentedManagedGCHandle, andSelfWeakReferenceis minted lazily — only once an object actually has an inheriting child or a registered callback.3. The disposal path is removed rather than left inert. With no finalizer,
BinderDisposehad no caller andIsDisposedwas permanentlyfalse. Both are deleted, along with_gate,_isDisposedand the now-unreachable guard inEventManager.RaiseLayoutUpdated. An always-false guard reads as a live safety check, which is worse than no guard.4. The offsets array is no longer over-rented.
DependencyPropertyDetailsCollection._entryOffsetsis indexed bybucketIndexalone, so it needsbucketIndex + 1slots — but it rented(bucketIndex * BucketSize) + 1, a 16× over-allocation. BecausebucketIndexderives fromDependencyProperty.UniqueId, a process-wide counter, the waste scaled with the highest property id an object touched: with ~2000 properties registered inUno.UIalone, aDependencyObjectthat set a late-registered property carried a 4 KBshort[]where 256 bytes suffice. The multiplier bought nothing —ArrayPoolalready rounds a request up to a power-of-two bucket, so growth stays geometric and resizes stay amortized O(1). This is independent of the finalizer work, but it is what turns item 1's lost pool returns into a net win rather than a trade (see the measurement below).Why the smaller rent is safe
The claim that
bucketIndex + 1is sufficient rests on_entryOffsetsnever being indexed by anything else, which is exhaustive rather than a spot check — the array has exactly three index sites, allbucketIndex:DependencyPropertyDetailsCollection.cs:174(read),:180(write) and:212(read, already guarded bybucketIndex < _entryOffsets.Length). Nothing indexes it byoffset + bucketRemainder; that is_entries, a different array.The resize path stays safe for the same reason it did before.
Utilities.GetMaxSizeForBucketis16 << binIndex, so a rent returns a power-of-two length of at least 16. The resize only runs whenbucketIndex >= entryOffsets.Length, so the new request (bucketIndex + 1) is strictly greater than the old length, and the returned array is at least that —entryOffsets.AsSpan().CopyTo(newOffsets)therefore cannot overflow, andUnsafe.InitBlockUnalignedstill has a non-empty array to fill. Growth remains geometric because the pool rounds up, so the* BucketSizemultiplier was buying nothing that the rounding did not already provide.Why holding the owner strongly is safe
The collection and its owner now form a reference cycle. That is safe only because the collection never escapes its owner — the cycle is then unreachable as a unit and a tracing GC reclaims it whole. This was verified rather than assumed:
DependencyObject._properties; its single pass-by-argument (CloneToForHotReload) is a stack local.DependencyPropertyDetails— which does escape constantly — carries no back-pointer to the collection or the owner. ABindingExpressionpinned by a long-lived ViewModel therefore pins details, not the element._hardOwnerReference = _ownerReference.Target, i.e. the owner itself — always a self-edge inside that same cycle. Clearing it on unload released nothing, which is why making it permanent is leak-neutral and why no leak test moved.The owner is now typed
DependencyObjectrather thanobject, and the invariant is stated on the field, so a future caller cannot quietly pass a foreign object and turn this into an unbounded pin.Does dropping the pool returns leak?
No, and it cannot. Neither pool tracks what it hands out —
LinearArrayPool.Bucket.TryPopnulls the slot on rent andDefaultArrayPoolBucketdoes the same — so an unreturned array is referenced only by the collection that rented it, and dies in the same collection as its owner.WeakReferencePoolsays so outright: ReturnedManagedWeakReferenceare not tracked by the pool and do not have to be returned.More fundamentally, a finalizer runs only on an object the GC has already proven unreachable, so it can never un-leak anything. Everything
BinderDisposedid was recycling — the callback manager's shadow array,HashtableExbuckets, pooled weak refs, the entries/offsets arrays. None of it broke a reference from a live root. The cost of dropping it is allocation churn, not retention — and that is measurable.Benchmark 📈
600k control-like DOs, 4 DPs each, Skia Desktop, across
dostore→ finalizer-drop → this branch:dostoreRead this carefully. The
40002 → 20002step (dropping the finalizer) is workload-independent. The20002 → 2step depends on objects never minting a self-handle, and the benchmark's DOs are parentless leaves — the best case. A real visual tree mints one for every element with an inheriting child (DependencyObject.Store.cs:826, 1009, 1176, 1225), so expect the real-world figure to land between the two columns. Worth re-measuring on a load/unload page before quoting the headline number.Allocation & GC measurement 📊
100,000
DependencyObjects created, properties set, dropped. 2048 properties are pre-registered first so the bucket index (127) lands where a real app's would rather than near zero. .NET 11 preview, x64, CoreCLR;GC.GetTotalAllocatedBytes(precise: true)andGC.CollectionCount.A — one high-id property per object
dostore(finalizer + pool returns)B — five properties spread across the id range
dostoreThree things fall out:
DependencyObjectpreviously survived the collection that found it dead and was promoted a generation, taking whole discarded subtrees with it. That is why throughput improves ~3× while allocating more.dostorebaseline the net is −66% allocated bytes in A and −24% in B, with gen1/gen2 collections down ~16×/4× and wall clock down 3.8×/1.7×. Both axes improve; nothing is traded.How this was measured. Three builds of
Uno.UI.UnitTestsat net11.0, each running the same throwaway harness (not committed — it is a measurement tool, not a test):dostored083fbain a separate worktree — finalizer present, pool returns live, original rente65d97f(this branch, before the rent fix)fbfead4(this branch, after)The harness registers 2048 padding properties, warms up 20k iterations to let each build's pool reach its own steady state, then brackets 100k iterations with
GC.GetTotalAllocatedBytes(precise: true)andGC.CollectionCount(0..2), forcingCollect / WaitForPendingFinalizers / Collectbetween scenarios so the finalizer build is not credited with work it deferred. Rebuilding the middle row rather than inferring it is what separates the finalizer's cost from the rent fix's benefit — the two changes pull in opposite directions and would otherwise be indistinguishable.Caveats: this is synthetic — bare
DependencyObjects in a tight loop, no visual tree or layout — so it isolates the property store rather than modelling a page, and real-world relative deltas will be smaller. Desktop CoreCLR only; WASM/Mono has a different collector and was not measured, though fewer finalizable objects and fewer bytes are strictly better there too. A "heap at end" column was collected and deliberately omitted: it is a snapshot taken at an arbitrary point relative to the last gen0 GC, and was too noisy to quote.Validation 🔍
Uno.UI,Uno.UI.UnitTests,Uno.UI.RuntimeTests.Skia,SamplesApp.Skia.Generic, net10.0;Uno.UI.UnitTestsat net11.0.When_Gregorian_*timezone failures. 0 regressions.When_Gregorian_FixedDate*Calendar/ICU failures.dostorebaseline and to the merge base. The one failure (When_Add_Remove(CommandBarFlyout_Leak, …)) is pre-existing, confirmed by building and runningaff73c4cseparately.Given_DependencyProperty_Propagation.When_Store_Populated_Then_Owner_Collectedpins the collectibility invariant — a populated store with an inheriting child is still reclaimed. Proven meaningful by negative control: inverting the owner assertion makes it fail with a non-null target, so it neither vacuously passes nor silently skips.Given_DependencyPropertyDetailsCollectionpins the offsets sizing. It fails before the fix with "512 slots for bucket index 17 (needs 18, tolerated 64)", and two companion tests grow the array from the top down and the bottom up, reading back every bucket it claims to cover, so a future resizing change cannot trade addressability for the smaller rental.Breaking changes ❗
No public API changes. Two behavioural notes, both Uno-only:
DependencyObjectis no longer finalizable. A derived type declaring its own finalizer previously chained into~DependencyObject; it no longer does. In-repo subclasses are unaffected (the base finalizer only recycled pooled objects).Timelineis updated accordingly — it can suppress its own finalization again, which it could not while a base finalizer existed.DependencyPropertyDetailsCollection.Disposewas reached only from the finalizer, so entries/offsets arrays now become gen0 garbage instead of being recycled. This cannot leak (see above); measured on its own it costs +15% allocation, and right-sizing the offsets rent more than repays it — the branch lands well below thedostorebaseline on both allocated bytes and collection count.PR Checklist ✅
Screenshots Compare Test Runresults.