Skip to content

Fix for handler leaks by traversing non-IView Shell nodes in DisconnectHandlers() - #38022

Merged
kubaflo merged 6 commits into
dotnet:inflight/currentfrom
BagavathiPerumal:fix-36584
Sep 10, 2026
Merged

kubaflo merged 6 commits into
dotnet:inflight/currentfrom
BagavathiPerumal:fix-36584

Conversation

@BagavathiPerumal

@BagavathiPerumal BagavathiPerumal commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab, causing BlazorWebView (and other native-resource-backed controls like WebView , HybridWebView , and GraphicsView ) to leak permanently once Window.Page is replaced.

When an application sets Window.Page = new Shell(...) and that Shell hosts a page containing a BlazorWebView , and later replaces Window.Page with a different page (a common pattern during login flows, onboarding-to-main-app transitions, or full app resets), the old Shell's visual tree is expected to be fully disconnected so its handlers — and the native resources they own — can be released and garbage collected. Instead, the teardown silently stops partway through the tree, so BlazorWebViewHandler.DisconnectHandler() is never invoked.

This is the only code path that starts WebViewManager.DisposeAsync() , so the WebViewManager , the native platform web view, and the entire rendered Blazor component tree are never disposed. Repeating this pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView screen multiple times) causes unbounded memory growth and can eventually crash the app.

Root cause

The issue stems from two independent defects that both had to be fixed to fully resolve the leak.

  1. Traversal gap (Core, all platforms). The internal tree-traversal helper that builds a flat list of every view in the visual tree, so their handlers can be safely disconnected afterward, only recursed into an element's visual children when the current element was itself an IView . ShellItem and ShellSection — the structural nodes Shell uses to organize its tabs — implement IVisualTreeElement (so they expose child elements) but do not implement IView (they have no handler of their own to disconnect). Because traversal was gated on is IView , the walk stopped dead as soon as it reached a ShellItem / ShellSection , and everything nested beneath it — the hosted ContentPage and any controls inside it, including BlazorWebView — was never visited and consequently never had its handler disconnected. This was a latent gap present since the disconnect traversal was first introduced; it went unnoticed because most existing call sites operate on already-homogeneous IView trees, and the one call site that walks through non- IView structural nodes — a Shell being torn down — produces no crash or visible symptom, only a silent, memory-profiler-visible leak.

  2. Incomplete native teardown (Android and Windows). Even once traversal correctly reached BlazorWebView and called its handler's disconnect method, each platform's handler implementation still had to release its own native resources — and two platforms did not do this fully:

• Android: the disconnect path never called Destroy() on the native WebView , never detached it from its parent view group, and never cleared its WebViewClient / WebChromeClient — all steps that MAUI's own non-Blazor WebView handler already performs, and that Android's own API docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but never called .Close() on the native WebView2 control; that call was only wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they only became reachable/observable once the traversal fix let the disconnect logic actually get called.

Solution description

Traversal fix (Core). The fix separates two responsibilities that had been incorrectly conflated: "should this element be collected for disconnection" and "should traversal continue past this element." The traversal now adds an element to the flat list only if that element is IView (preserving the original disconnect behavior for real views), but unconditionally recurses into its visual children regardless of whether the current element itself is an IView . This means structural, non- IView nodes like ShellItem / ShellSection are still traversed through — just not added to the disconnect list themselves — so traversal can reach the real IView descendants nested beneath them and disconnect their handlers as intended. Because this change is confined to shared, platform-agnostic traversal logic with no platform-specific conditionals, it uniformly fixes reachability for every control affected by the same pattern.

Platform teardown fixes (Android and Windows). With the disconnect path now reliably reached, each platform's handler was updated to fully release native resources on disconnect:

• Android: the handler now performs the same teardown sequence as the Core WebView handler — clearing WebViewClient / WebChromeClient , detaching the WebView from its parent, removing all views, and calling Destroy() . Since Blazor's JS-driven component disposal needs the native WebView to stay alive until its async disposal completes, the destroy step is deferred as a continuation on the disposal task (or run synchronously when blocking disposal is configured), guaranteeing native cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native WebView2 control as part of disconnect, rather than relying solely on app-shutdown teardown, so the control is released as soon as the BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and the Android/Windows  BlazorWebView  teardown, this PR also updates  ShellRenderer.DisconnectHandler()  on iOS. Previously this method was empty, so when a Shell was disconnected, the currently-active  ShellItemRenderer  (and everything it hosts, including any  BlazorWebView ) was never disconnected or disposed on iOS, and the  Element / Handler  back-references were never cleared. The fix now: unsubscribes from  Element.PropertyChanged , disconnects and disposes the current  IShellItemRenderer  (removing its view from the superview and its view controller from the parent controller), disposes the  ShellRenderer  itself, clears the  Element 's  Handler  reference (if still pointing at this renderer), and nulls out  Element / _mauiContext . This closes the same class of leak on iOS that the Core traversal fix closes for Android/Windows, and is required for the fix to be complete across all four validated platforms.

Together, these changes ensure the visual tree is walked correctly, disconnect logic is invoked for every affected control, and each platform's handler fully releases its native resources — closing the leak end-to-end. The Android fix has been empirically verified against the customer's own leak-probe sample (no leak detected across repeated passes); the Windows fix is code-reviewed but not yet verified on a physical/emulated Windows environment.

Validated the behavior in the following platforms

  • iOS
  • Mac
  • Android
  • Windows

Issues Fixed

Fixes #36584

Output ScreenShot

Platform Before After
Mac
36584-Mac-BeforeFix.mov
36584-Mac-AfterFix.mov
iOS
36584-iOS-BeforeFix.mov
36584-iOS-AfterFix.mov
Windows
36584-BeforeFix.Windows.mp4
36584-AfterFix.Windows.mp4
Android
36584-Android-BeforeFix.mov
36584-Android-AfterFix.mov

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 38022

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 38022"

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@BagavathiPerumal BagavathiPerumal added the community ✨ Community Contribution label Aug 31, 2026
@dotnet-policy-service dotnet-policy-service Bot added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Aug 31, 2026
@BagavathiPerumal BagavathiPerumal added do-not-merge Don't merge this PR and removed partner/syncfusion Issues / PR's with Syncfusion collaboration labels Aug 31, 2026
@BagavathiPerumal BagavathiPerumal added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Aug 31, 2026
@github-actions github-actions Bot added area-blazor Blazor Hybrid / Desktop, BlazorWebView platform/android platform/windows labels Aug 31, 2026
@vishnumenon2684

Copy link
Copy Markdown
Contributor

/azp run maui-pr-uitests , maui-pr-devicetests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).

@vishnumenon2684

Copy link
Copy Markdown
Contributor

/azp run maui-pr-uitests , maui-pr-devicetests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).

…des, causing BlazorWebView/WebView/GraphicsView handler leaks
…DisconnectHandler() implementation to disconnect and dispose of the current Shell item renderer.
@vishnumenon2684

Copy link
Copy Markdown
Contributor

/azp run maui-pr-uitests , maui-pr-devicetests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).

@BagavathiPerumal BagavathiPerumal changed the title [WIP]Fix for handler leaks by traversing non-IView Shell nodes in DisconnectHandlers() Fix for handler leaks by traversing non-IView Shell nodes in DisconnectHandlers() Sep 7, 2026
@BagavathiPerumal

Copy link
Copy Markdown
Contributor Author

AI Review Summary

@BagavathiPerumal — new AI review results are available based on commit 972d7d4.

Gate Passed Confidence Medium Platform iOS

🗂️ Review Sessions — click to expand

🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: IOS · Base: main · Merge base: f7bfa2a5

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 HandlerLifeCycleTests HandlerLifeCycleTests ✅ FAIL — 33s ✅ PASS — 20s
🔴 Without fix — 🧪 HandlerLifeCycleTests: FAIL ✅ · 33s
Error-relevant lines (filtered from the build log):

     at Microsoft.Maui.Controls.Core.UnitTests.HandlerLifeCycleTests.DisconnectHandlersReachesPageInsideShell() in /_/src/Controls/tests/Core.UnitTests/HandlerLifeCycleTests.cs:line 116
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)

🟢 With fix — 🧪 HandlerLifeCycleTests: PASS ✅ · 20s
(no coded error found; showing last 1200 chars)

projects to restore...
  All projects are up-to-date for restore.
Test run for /Users/cloudtest/vss/_work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.2 (arm64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.13)
[xUnit.net 00:00:00.09]   Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:00.63]   Discovered:  Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:00.63]   Starting:    Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:00.72]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Passed ChangingAndChangedBothFireInitially [7 ms]
  Passed SettingHandlerToNullDisconnectsHandlerFromVirtualView [31 ms]
  Passed BasicVisualTreeDisconnects [9 ms]
  Passed ChangingArgsAreSetCorrectly [< 1 ms]
  Passed InterruptDisconnect [< 1 ms]
  Passed DisconnectHandlersReachesPageInsideShell [20 ms]
  Passed SettingNewHandlerDisconnectsOldHandler [1 ms]
Test Run Successful.
Total tests: 7
     Passed: 7
 Total time: 0.9946 Seconds

📁 Fix files reverted (5 files)

  • src/BlazorWebView/src/Maui/Android/BlazorWebViewHandler.Android.cs
  • src/BlazorWebView/src/Maui/Windows/BlazorWebView.Windows.cs
  • src/BlazorWebView/src/Maui/Windows/BlazorWebViewHandler.Windows.cs
  • src/Controls/src/Core/Compatibility/Handlers/Shell/iOS/ShellRenderer.cs
  • src/Core/src/ViewExtensions.cs

📋 Pre-Flight — Context & Validation

PR #38022 Pre-Flight

Context

Independent Diff Inspection

The PR changes six files:

  1. src/Core/src/ViewExtensions.cs changes BuildFlatList to accept any object, add only IView nodes to the disconnect list, and continue recursively through every IVisualTreeElement.
  2. src/Controls/tests/Core.UnitTests/HandlerLifeCycleTests.cs adds DisconnectHandlersReachesPageInsideShell, which constructs Shell -> ShellItem -> ShellSection -> ShellContent -> ContentPage -> Button and verifies the Shell, page, and button handlers are disconnected.
  3. src/Controls/src/Core/Compatibility/Handlers/Shell/iOS/ShellRenderer.cs implements renderer teardown, including event unsubscription, current item renderer disconnection/disposal, parent/view removal, handler clearing, and context clearing.
  4. src/BlazorWebView/src/Maui/Android/BlazorWebViewHandler.Android.cs defers native WebView destruction until Blazor disposal completes, then detaches clients/parent and destroys the native view.
  5. src/BlazorWebView/src/Maui/Windows/BlazorWebViewHandler.Windows.cs defers guarded WebView2.Close() until Blazor disposal completes.
  6. src/BlazorWebView/src/Maui/Windows/BlazorWebView.Windows.cs routes window-destroy teardown through the same guarded close helper.

The primary issue and executable regression test concern the shared traversal gap. The platform teardown additions are independent extensions of the PR and are not directly exercised by the detected test.

Bounded Test Surface

Use only:

dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HandlerLifeCycleTests"

This runs the detected primary test DisconnectHandlersReachesPageInsideShell plus the six existing HandlerLifeCycleTests regression tests. The gate recorded one expected failure without the fix and all seven tests passing with the PR fix. Do not run UI tests, device tests, the gate, or a broader suite.

Try-Fix Boundaries

EstablishBrokenBaseline.ps1 previously identified these five production fix files as restorable:

  • src/BlazorWebView/src/Maui/Android/BlazorWebViewHandler.Android.cs
  • src/BlazorWebView/src/Maui/Windows/BlazorWebView.Windows.cs
  • src/BlazorWebView/src/Maui/Windows/BlazorWebViewHandler.Windows.cs
  • src/Controls/src/Core/Compatibility/Handlers/Shell/iOS/ShellRenderer.cs
  • src/Core/src/ViewExtensions.cs

The retained test file is read-only during alternative attempts. Each attempt must use a different mechanism from the PR and from earlier candidates, perform one implementation/test pass with at most one focused correction/retest, capture its artifacts, and restore exclusively with pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore.

🔬 Code Review — Deep Analysis

Code Review — PR #38022

Independent Assessment

What this changes: The PR makes DisconnectHandlers() continue through non-IView visual-tree nodes so Shell-hosted pages are included in the stable disconnect list. It also completes native teardown for Android and Windows BlazorWebView handlers and adds explicit teardown to the iOS compatibility ShellRenderer.

Inferred motivation: Replacing a Window.Page that contains a Shell must disconnect descendant handlers and release platform WebView resources instead of retaining the old page, rendered Blazor components, and native controls.

Reconciliation with PR Narrative

The implementation matches the stated traversal defect and the platform cleanup described in the PR. The focused regression test directly distinguishes the old traversal from the new behavior: it fails at the Shell-hosted page without the fix and all seven HandlerLifeCycleTests pass with the submitted PR.

Prior Review Reconciliation

Prior finding Status Evidence
Android continuation was unobserved ✅ Fixed DestroyPlatformViewAfterDisposalAsync(...).FireAndForget(_logger) now observes and logs continuation failures.
Windows closed WebView2 before asynchronous disposal ✅ Fixed CloseWebView2AfterDisposalAsync now waits for disposal before closing in the non-blocking path.
Windows teardown exceptions lacked logging ✅ Fixed Both fire-and-forget tasks now receive the cached Logger.
iOS ShellRenderer retains _incomingRenderer ❌ Unresolved SetCurrentShellItemControllerAsync assigns _incomingRenderer, but the new disconnect path clears only _currentShellItemRenderer. In the stable case it retains the disposed renderer; during an in-flight transition the continuation can pass the _incomingRenderer != value guard and then evaluate Shell.CurrentItem after Element has been cleared.
The single MAUI expert-reviewer pass wrote inline-findings.json as an empty array; no additional file-line findings survived its validation.

Blast Radius Assessment

  • Runs for all instances: Shared traversal changes every DisconnectHandlers() walk; native cleanup runs only when the affected handlers disconnect.
  • Startup impact: None.
  • Static/shared state: None added.
  • Lifecycle impact: High enough to require explicit disconnect/reconnect reasoning because the PR changes Shell renderer and platform handler teardown.

CI and Gate Evidence

  • Trusted gate: Passed. The focused test fails without the traversal fix and all seven HandlerLifeCycleTests pass with it.
  • Deep iOS UI tests: 356 passed, one unrelated editor element-lookup failure, and eight skipped.
  • Regression cross-reference: Clean; no overlapping recent labeled bug-fix changes were detected.

Findings

❌ Error — Clear the pending Shell item renderer during disconnect

ShellRenderer.DisconnectHandler() leaves _incomingRenderer populated. A completed transition leaves it pointing at the same renderer that the disconnect path has just disposed. More importantly, if disconnect happens while SetCurrentShellItemControllerAsync awaits _activeTransition, the continuation still sees _incomingRenderer == value, proceeds to this.Shell.CurrentItem after Element = null, and can fail before disposing the incoming renderer. Clearing _incomingRenderer during disconnect both releases the stale reference and causes the continuation's existing supersession guard to take its safe disposal branch.

Failure-Mode Probing

  • Non-Shell trees: The traversal still adds and disconnects only IView instances; non-IView nodes are traversal bridges only.
  • Manual policy boundary: The policy check remains before both collection and recursion, so a manual-disconnect node still protects its entire subtree.
  • Handler disconnect/reconnect: Android and Windows teardown captures the old platform view and client state locally before handler fields are cleared. The iOS renderer needs the _incomingRenderer reset described above to make an in-flight transition recognize disconnect as supersession.
  • Null parent/platform view: Android parent removal is conditional; Windows close is guarded for an uninitialized or already-disposed CoreWebView2.
  • External output contract: Not applicable.
  • Trim/AOT evidence chain: Not applicable.

Verdict: NEEDS_CHANGES

Confidence: medium

Summary: The shared traversal fix is direct and gate-proven, and the native WebView cleanup follows the correct dispose-before-destroy ordering. One small iOS lifecycle correction is still warranted before preferring this implementation: clear _incomingRenderer when disconnect begins so disposed or pending renderers cannot survive the teardown boundary.

🛠️ Try-Fix — Analysis & Comparison

Try-Fix Alternatives for PR #38022

Candidate 1 — Handler-Centric Visual-Tree Walk

Model: gpt-5.3-codex Result: Blocked

Candidate 1 planned to traverse nodes as IVisualTreeElement and disconnect visited nodes that are IElement instances with a handler. Unlike the PR's widened object recursion plus IView accumulator, this would change disconnect eligibility from IView membership to handler-owning IElement membership while treating non-handler Shell nodes only as traversal carriers.

The attempt could not establish its required baseline because the checkout already contained extensive pre-existing trusted/harness modifications. EstablishBrokenBaseline.ps1 stopped with DIRTY WORKING DIRECTORY, did not create .github/.baseline-state.json, and therefore provided no RevertedFiles allow-list. No production code was edited and the bounded HandlerLifeCycleTests command was not run. The exact restore command completed with the accepted no-state result, No baseline state found.

Files changed: None Self-review: 0 findings; no candidate diff existed.

Full narrative: CustomAgentLogsTmp/PRState/38022/PRAgent/try-fix-1/content.md Artifacts: CustomAgentLogsTmp/PRState/38022/PRAgent/try-fix/attempt-1

Candidate 2 — Non-IView Frontier Projection

Model: gpt-5.6-sol Result: Pass

Candidate 2 preserves BuildFlatList(IView, List<IView>) and the existing IView-only disconnect model. A separate GetChildViews iterator yields direct IView children and recursively projects through non-IView visual-tree nodes until reaching the next IView frontier. Manual disconnect policy prunes either kind of child before projection.

This differs from both earlier mechanisms: the PR carries every node type through one widened object recursion, while Candidate 1 proposed changing disconnect eligibility to handler-owning IElement nodes. Candidate 2 instead keeps structural Shell nodes outside the flatten/disconnect recursion entirely and collapses each structural chain into its next reachable IView children.

Files changed by the candidate: src/Core/src/ViewExtensions.cs Test: dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~HandlerLifeCycleTests" Result: 7 passed, 0 failed, 0 skipped; one implementation/test pass and no correction. Self-review: 0 findings. Restore: Restored True; all five baseline target files matched HEAD afterward.

The permitted test regenerated src/Core/src/Handlers/HybridWebView/HybridWebView.js as an unrelated build side effect. It is retained in the mandatory raw fix.diff because the restore-only contract prohibited cleaning files outside the baseline allow-list; it is not part of this candidate.

diff --git a/src/Core/src/ViewExtensions.cs b/src/Core/src/ViewExtensions.cs
index 73b30adebf..bd34e1b7fd 100644
--- a/src/Core/src/ViewExtensions.cs
+++ b/src/Core/src/ViewExtensions.cs
@@ -55,12 +55,32 @@ namespace Microsoft.Maui
 
 				if (view is IVisualTreeElement vte)
 				{
-					foreach (var child in vte.GetVisualChildren())
+					foreach (var childView in GetChildViews(vte))
 					{
-						if (child is IView childView)
-						{
-							BuildFlatList(childView, flatList);
-						}
+						BuildFlatList(childView, flatList);
+					}
+				}
+			}
+
+			IEnumerable<IView> GetChildViews(IVisualTreeElement element)
+			{
+				foreach (var child in element.GetVisualChildren())
+				{
+					if (child is IHandlerDisconnectPolicies handlerProperties &&
+						handlerProperties.DisconnectPolicy == HandlerDisconnectPolicy.Manual)
+					{
+						continue;
+					}
+
+					if (child is IView childView)
+					{
+						yield return childView;
+						continue;
+					}
+
+					foreach (var descendantView in GetChildViews(child))
+					{
+						yield return descendantView;
 					}
 				}
 			}

Full narrative, including the complete raw diff with generated build drift: CustomAgentLogsTmp/PRState/38022/PRAgent/try-fix-2/content.md Artifacts: CustomAgentLogsTmp/PRState/38022/PRAgent/try-fix/attempt-2

📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the description is unusually thorough and should be preserved, but the title omits the Android, Windows, and iOS/MacCatalyst teardown work, while the description counts only two root causes despite documenting a third iOS Shell renderer gap and describes the deferred Windows close as unconditional.

Recommended title

[All] Shell/BlazorWebView: Disconnect nested handlers and release native views

Recommended description

### Issue Details

`DisconnectHandlers()` never reaches pages hosted inside a `Shell` tab, causing `BlazorWebView` (and other native-resource-backed controls such as `WebView`, `HybridWebView`, and `GraphicsView`) to leak after `Window.Page` is replaced.

When an application sets `Window.Page = new Shell(...)`, hosts a page containing a `BlazorWebView`, and later replaces `Window.Page` with another page (for example, during login, onboarding-to-main-app transitions, or a full app reset), the old Shell visual tree should be disconnected so its handlers and native resources can be released. Instead, teardown stops at Shell structural nodes, so `BlazorWebViewHandler.DisconnectHandler()` is never invoked.

That disconnect path starts `WebViewManager.DisposeAsync()`. When it is not reached, the `WebViewManager`, native platform web view, rendered Blazor component tree, and associated application state remain alive. Repeating the transition causes unbounded memory growth and can eventually crash the app.

### Root cause

The leak has three related teardown gaps:

1. **Traversal gap (Core, all platforms).** The helper that builds a stable list of views for disconnection recursed into visual children only when the current element implemented `IView`. `ShellItem` and `ShellSection` implement `IVisualTreeElement`, but not `IView`, so traversal stopped before reaching the hosted `ContentPage` and controls such as `BlazorWebView`. This latent gap produced no immediate exception; it appeared as a memory-profiler-visible leak.

2. **Incomplete native `BlazorWebView` teardown (Android and Windows).** Once traversal reaches `BlazorWebView`, each handler must release its platform resources:
   - **Android:** The disconnect path did not call `Destroy()` on the native `WebView`, detach it from its parent, remove its child views, or clear its `WebViewClient` and `WebChromeClient`.
   - **Windows:** The disconnect path disposed the managed WebView manager but did not close the native WebView2 control. Closing was wired only to application shutdown, not per-instance disconnect.

3. **Incomplete Shell renderer teardown (iOS and MacCatalyst).** `ShellRenderer.DisconnectHandler()` was empty, so the active `ShellItemRenderer` was not disconnected or disposed and the `Element`/`Handler` references were not cleared when a Shell was torn down.

### Description of Change

#### Shared traversal

`ViewExtensions.DisconnectHandlers()` now separates two decisions:

- Add an element to the stable disconnect list only when it implements `IView`.
- Continue through its visual children whenever it implements `IVisualTreeElement`, even when the current node is not an `IView`.

This lets structural nodes such as `ShellItem` and `ShellSection` act as traversal bridges without making them disconnect targets. The walk reaches the hosted page and all real `IView` descendants while preserving manual-disconnect subtree boundaries.

#### Android `BlazorWebView`

The handler now:

- Stops loading and captures the current `WebViewClient` and `WebChromeClient`.
- Waits for Blazor/JavaScript disposal before native destruction in the default non-blocking path.
- Clears the native clients, removes the `WebView` from its parent, removes child views, calls `Destroy()`, and disposes the captured clients.
- Performs the same cleanup synchronously after blocking disposal, or immediately when no `WebViewManager` was created.
- Routes fire-and-forget tasks through the existing logging helper so teardown failures are observed.

The native `WebView` remains alive until Blazor disposal completes, avoiding interruption of JavaScript-driven component teardown.

#### Windows `BlazorWebView`

The handler now closes WebView2:

- After asynchronous Blazor disposal completes in the default non-blocking path.
- Immediately after blocking disposal completes.
- Immediately when no `WebViewManager` was created.

`Window.Destroying` and handler disconnect share the guarded `CloseWebView2` helper, which tolerates an uninitialized or already-disposed control. Teardown task failures are routed through the logger.

#### iOS and MacCatalyst `ShellRenderer`

`ShellRenderer.DisconnectHandler()` now:

- Unsubscribes from `Element.PropertyChanged`.
- Disconnects and disposes the current `IShellItemRenderer`.
- Removes its view from the superview and its view controller from the parent controller.
- Disposes the `ShellRenderer`.
- Clears the `Element.Handler` reference when it still points to this renderer.
- Clears `Element` and `_mauiContext`.

Together, these changes ensure the Shell visual tree is traversed, descendant handlers are invoked, and platform resources are released when the old `Window.Page` is replaced.

### Regression coverage

`DisconnectHandlersReachesPageInsideShell` constructs:

`Shell -> ShellItem -> ShellSection -> ShellContent -> ContentPage -> Button`

It verifies that disconnecting the Shell also disconnects the hosted page and button handlers. This test directly covers the shared traversal defect; the platform-specific native teardown remains separate from this unit-test surface.

The Android behavior was also checked against the customer's leak-probe sample across repeated passes.

### Platforms validated

- [x] iOS
- [x] MacCatalyst
- [x] Android
- [x] Windows

### Issues Fixed

Fixes https://github.com/dotnet/maui/issues/36584

### Output ScreenShots

| Platform | Before | After |
|---|---|---|
| MacCatalyst | <video src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb"> | <video src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404"> |
| iOS | <video src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb"> | <video src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b"> |
| Windows | <video src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0"> | <video src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2"> |
| Android | <video src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1"> | <video src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d"> |

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr-plus-reviewer

The submitted PR has the strongest overall design: its shared traversal fix is direct, preserves the existing IView disconnect eligibility, and is paired with the Android, Windows, and iOS teardown needed to release the resources that become reachable. The reviewer-enhanced candidate keeps that complete scope and adds one lifecycle-critical line, clearing _incomingRenderer when the iOS ShellRenderer disconnects.

Candidate comparison

Rank Candidate Regression result Scope and correctness Review outcome
1 pr-plus-reviewer PASS — 7/7 HandlerLifeCycleTests Keeps the submitted shared and platform teardown fixes; also prevents a disposed or pending _incomingRenderer from surviving disconnect or resuming against Element = null. One-line reviewer patch; diff --check clean.
2 pr PASS — trusted Gate fails without the fix and passes 7/7 with it Correctly reaches Shell-hosted views and completes Android/Windows/iOS teardown, but leaves _incomingRenderer rooted after a stable transition and unsafe across an in-flight transition. Expert pass produced no new inline comments, but prior-review reconciliation confirmed the unresolved iOS lifecycle state.
3 try-fix-2 PASS — 7/7 Its non-IView frontier projection solves the tested traversal defect while retaining BuildFlatList(IView, ...). It is more complex than the PR's single recursive walk and, because it restores the other production files, omits the submitted iOS renderer teardown and Android/Windows native WebView cleanup. Its raw artifact also contains unrelated generated HybridWebView.js drift. Clean self-review, but incomplete for the full leak-remediation scope.
4 try-fix-1 BLOCKED — tests not run Proposed changing disconnect eligibility from IView to handler-owning IElement, which broadens semantics beyond what the issue requires. No implementation or candidate diff was produced. Baseline creation failed on the dirty checkout.

Why pr-plus-reviewer wins

  1. It passes the same bounded regression set as every validated candidate.
  2. It retains the PR's simpler traversal model and complete native teardown work rather than solving only the unit-tested traversal slice.
  3. It resolves the remaining iOS state transition precisely: setting _incomingRenderer = null releases the stable reference and makes a pending continuation enter its existing superseded-renderer disposal branch.
  4. Its reviewer delta is one source line, contains no generated drift, and requires no unrelated behavior change.

Required PR change

Apply pr-plus-reviewer/reviewer.patch to the submitted PR. Because the winning candidate differs from the submitted pr, the PR should not be approved as-is.

Evidence boundaries

  • Trusted Gate: HandlerLifeCycleTests fail without the submitted traversal fix and pass with it.
  • pr-plus-reviewer: 7 passed, 0 failed, 0 skipped from the prescribed candidate worktree.
  • try-fix-2: 7 passed, 0 failed, 0 skipped in its recorded attempt.
  • try-fix-1: blocked before edits and validation; it is ranked below every passing candidate.
  • No full suite was run.

📱 UI Tests — Button,Label,Layout

Detected UI test categories: Button,Label,Layout

❌ Deep UI tests — 357 passed, 1 failed, 8 skipped across 3 categories on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
Button 73/74 (1 skipped) ✓ —
Label 90/92 (2 skipped) ✓ —
Layout 194/200 (1 ❌, 5 skipped) —
🔍 AI analysis of failures — PR-related vs unrelated

🔍 AI-generated triage (GitHub Copilot CLI) — a heuristic judgement of whether each deep UI test failure is connected to this PR's changes. Verify before relying on it.

Likely unrelated: the failures appear pre-existing, flaky, or infrastructure.

  • ● Unrelated — iOS Editor keyboard-scrolling layout (~1 test): the test exercises Editor visibility and keyboard automation inside a NavigationPage, while the PR's iOS change is limited to Shell disconnection and its shared traversal change only affects handler teardown, with the generic Appium element-lookup failure referencing neither path.

❌ Layout — 1 failed test

EditorsScrollingPageTest

OpenQA.Selenium.NoSuchElementException : An element could not be located on the page using the given search parameters.; For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
at OpenQA.Selenium.WebDriver.UnpackAndThrowOnError(Response errorResponse, String commandToExecute)
   at OpenQA.Selenium.WebDriver.ExecuteAsync(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Appium.AppiumDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.WebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Appium.AppiumDriver.FindElement(String by, String value)
   at OpenQA.Selenium.Appium.MobileBy.FindElement(ISearchContext context)
   at OpenQA.Selenium.WebDriver.FindElement(By by)
   at OpenQA.Selenium.Appium.AppiumDriver.FindElement(By by)
   at Microsoft.Maui.TestCases.Tests.KeyboardScrolling.CloseiOSEditorKeyboard(AppiumDr
...

📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

🧭 Next Steps — reviewer changes required

I have fixed the issue "ShellRenderer.DisconnectHandler() never clears _incomingRenderer" via merge ShellRenderer.cs now uses upstream's Disconnect(), which clears _incomingRenderer and handles this case.

@BagavathiPerumal

Copy link
Copy Markdown
Contributor Author

Could you please resolve conflicts with inflight/current?

@kubaflo, I have resolved the conflict on this PR.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 10, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AI Review Summary

@BagavathiPerumal — new AI review results are available based on commit 72ead6d.

Gate Passed Confidence Unknown Platform iOS


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: IOS · Base: inflight/current · Merge base: 5ef20480

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 HandlerLifeCycleTests HandlerLifeCycleTests ✅ FAIL — 36s ✅ PASS — 31s
🔴 Without fix — 🧪 HandlerLifeCycleTests: FAIL ✅ · 36s

Error-relevant lines (filtered from the build log):

     at Microsoft.Maui.Controls.Core.UnitTests.HandlerLifeCycleTests.DisconnectHandlersReachesPageInsideShell() in /_/src/Controls/tests/Core.UnitTests/HandlerLifeCycleTests.cs:line 116
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
🟢 With fix — 🧪 HandlerLifeCycleTests: PASS ✅ · 31s

(no coded error found; showing last 1200 chars)

g projects to restore...
  All projects are up-to-date for restore.
Test run for /Users/cloudtest/vss/_work/1/s/artifacts/bin/Controls.Core.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Core.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.2 (arm64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.13)
[xUnit.net 00:00:00.14]   Discovering: Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:00.77]   Discovered:  Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:00.78]   Starting:    Microsoft.Maui.Controls.Core.UnitTests
[xUnit.net 00:00:00.95]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Passed ChangingAndChangedBothFireInitially [25 ms]
  Passed SettingHandlerToNullDisconnectsHandlerFromVirtualView [51 ms]
  Passed BasicVisualTreeDisconnects [16 ms]
  Passed ChangingArgsAreSetCorrectly [1 ms]
  Passed InterruptDisconnect [1 ms]
  Passed DisconnectHandlersReachesPageInsideShell [44 ms]
  Passed SettingNewHandlerDisconnectsOldHandler [2 ms]
Test Run Successful.
Total tests: 7
     Passed: 7
 Total time: 1.3172 Seconds
📁 Fix files reverted (4 files)
  • src/BlazorWebView/src/Maui/Android/BlazorWebViewHandler.Android.cs
  • src/BlazorWebView/src/Maui/Windows/BlazorWebView.Windows.cs
  • src/BlazorWebView/src/Maui/Windows/BlazorWebViewHandler.Windows.cs
  • src/Core/src/ViewExtensions.cs

📋 Pre-Flight — Context & Validation

Issue: #36584 - iOS: DisconnectHandlers() never reaches pages inside a Shell - BlazorWebView/WebViewManager leak permanently when Window.Page is replaced
PR: #38022 - Fix for handler leaks by traversing non-IView Shell nodes in DisconnectHandlers()
Target Platform: iOS
Base: inflight/current
PR Head: 72ead6d15d7982b88aac4171e9009884876b7e53
Files Changed: 4 implementation, 1 unit test

Problem Context

  • DisconnectHandlers() currently descends only through visual children that implement IView. Shell structural nodes such as ShellItem and ShellSection implement IVisualTreeElement but not IView, so traversal stops before reaching tab pages and controls beneath them.
  • On the reported iOS scenario, replacing Window.Page leaves the old Shell-hosted BlazorWebView handler and WebViewManager reachable. Directly invoking Handler.DisconnectHandler() releases most tracked objects, while the extension path does not.
  • The reporter removed an accidental HandlerDisconnectPolicy.Manual setting and reproduced the leak with the default Automatic policy. They also warned that blocking Blazor disposal on the UI thread deadlocks.

Current PR Diff

File Role Current PR approach
src/Core/src/ViewExtensions.cs Shared implementation Accept any object during traversal, collect only IView nodes, and recurse through every IVisualTreeElement.
src/BlazorWebView/src/Maui/Android/BlazorWebViewHandler.Android.cs Android implementation Defer native WebView detach/destroy and client disposal until Blazor disposal finishes.
src/BlazorWebView/src/Maui/Windows/BlazorWebView.Windows.cs Windows implementation Route window-destroy teardown through a guarded shared close helper.
src/BlazorWebView/src/Maui/Windows/BlazorWebViewHandler.Windows.cs Windows implementation Defer WebView2 close until Blazor disposal finishes and log fire-and-forget failures.
src/Controls/tests/Core.UnitTests/HandlerLifeCycleTests.cs Unit test Add DisconnectHandlersReachesPageInsideShell, covering Shell -> ShellItem -> ShellSection -> ShellContent -> ContentPage -> Button.

The current five-file PR diff contains no iOS-specific ShellRenderer change, although the PR narrative and older review discussion still describe one that existed in an earlier commit.

Validation Inputs for Try-Fix

  • Gate: PASSED - the detected test fails without the PR fix and passes with it.
  • Primary test command: dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --configuration Debug --logger "console;verbosity=normal" -p:TreatWarningsAsErrors=false --filter "HandlerLifeCycleTests"
  • Observed primary result with PR fix: 7 passed, 0 failed.
  • Mandatory regression tests: None. The mechanical regression cross-reference found no overlap with recent labeled bug-fix PRs.
  • Gate verification must not be rerun.

Review Boundary

The dedicated expert review is deferred to STEP 5b by contract. No expert-review agent was launched and no code-review verdict is asserted here.

Existing Approach to Avoid Repeating

The PR's shared traversal fix changes the recursive helper from IView input to a general object, adds only IView instances to the disconnect list, and unconditionally walks IVisualTreeElement.GetVisualChildren(). Each try-fix candidate must use a mechanism-level alternative rather than restating this implementation.


🔬 Code Review — Deep Analysis

Expert PR Evaluation

Initial expert verdict: NEEDS_DISCUSSION with low confidence because the reviewer could not independently determine the required-check state. This was an evidence limitation, not a concrete defect in the submitted fix. The workflow-provided Gate is trusted as passed.

Inline findings: None. inline-findings.json contains a valid empty JSON array.

Independent assessment

The shared DisconnectHandlers traversal now crosses any IVisualTreeElement, including Shell structural nodes that do not implement IView, while collecting and disconnecting handlers only from actual IView instances. This closes the Shell traversal gap without attempting to disconnect handler-less structural nodes.

The Android and Windows BlazorWebView changes preserve asynchronous manager disposal before native teardown. Android then detaches and destroys the native WebView and disposes its clients; Windows closes WebView2 through the guarded shared close path. The continuation-based teardown avoids synchronously blocking the UI thread.

The new DisconnectHandlersReachesPageInsideShell test directly exercises the relevant Shell-to-page traversal. The trusted Gate confirms the test fails without the submitted fix and passes with it.

Risk assessment

  • The shared traversal change affects all DisconnectHandlers callers, but preserves manual-disconnect subtree pruning and the existing leaf-to-root disconnect order.
  • No new static state, subscriptions, startup behavior, or public API surface is introduced.
  • Disconnect/reconnect and null-handler cases continue to use existing handler checks; non-IView nodes are traversal-only.
  • Prior review surfaces contained no unresolved error-level issue on the current submitted diff.

Reviewer feedback

No actionable file:line issue or concrete implementation improvement was identified. A source refinement for pr-plus-reviewer is therefore not warranted; it should remain equivalent to the submitted PR candidate.

CI reconciliation

Anonymous GitHub/AzDO retrieval subsequently resolved the reviewer's check-state gap. The current PR head's maui-pr build 1590515 is red, but the latest inflight/current baseline build 1590052 is red with the same CS1061 errors at unchanged src/BlazorWebView/src/Maui/iOS/BlazorWebViewHandler.iOS.cs:322 for iOS and Mac Catalyst. The pack-stage missing-native-artifact failure follows those failed builds. These failures are pre-existing on the base and are not caused by the five-file PR diff.

With the CI failures classified as PR-unrelated, the reconciled code recommendation is LGTM with low confidence, consistent with the code-review skill's confidence cap for red-but-baseline-matched CI.


🛠️ Try-Fix — Analysis & Comparison

Try-Fix Candidates

Candidate Model Approach Result Primary Test Files Changed
1 gpt-5.3-codex Explicitly bridge known Shell structural nodes while retaining typed IView recursion Blocked Not run None
2 gpt-5.6-sol Project across non-IView nodes only until the next typed IView frontier Blocked Not run None

Candidate 1 - Shell Structural Enumeration

Result: Blocked

The candidate planned to retain BuildFlatList(IView, List<IView>), explicitly enumerate the Shell -> ShellItem -> ShellSection -> ShellContent structural path, and resume ordinary typed IView recursion at hosted pages and controls.

Prior PR mechanism avoided: The current PR broadens the recursive helper to object, conditionally collects IView nodes, and universally traverses every IVisualTreeElement. Candidate 1 instead proposed a Shell-specific bridge rather than object-wide visual-tree recursion.

Files changed: None.

Test result: The primary HandlerLifeCycleTests command was not run. EstablishBrokenBaseline.ps1 rejected the pre-existing dirty tracked reviewer-infrastructure overlay before creating .github/.baseline-state.json; the skill therefore prohibited implementation edits or testing.

Failure analysis: Environment-blocked before implementation. The required final restore command ran and reported that no baseline state existed (Restored=False). This does not establish whether the proposed mechanism would pass.

Inline self-review: 0 findings; there was no code diff.

Captured diff:

Full candidate narrative: ../try-fix-1/content.md

Candidate 2 - Non-IView Frontier Projection

Result: Blocked

The candidate planned to preserve BuildFlatList(IView, List<IView>) and add a separate frontier projector. Direct IView children would return to typed recursion; only non-IView structural children would be searched until the next IView frontier. Manual disconnect policy would prune either kind of subtree.

Prior mechanisms avoided: Unlike the PR, candidate 2 would not broaden the disconnect collector to object and recursively process every node type in one helper. Unlike candidate 1, it would not hard-code or enumerate Shell types.

Mechanism-level difference: Generic non-IView visual nodes become transparent edges only until an IView is reached; ordinary typed recursion then owns that view and its descendants. This separates structural projection from handler-disconnect collection.

Files changed: None.

Test result: The primary HandlerLifeCycleTests command was not run. Baseline setup encountered the same pre-existing dirty reviewer-infrastructure overlay and created no .github/.baseline-state.json.

Failure analysis: Environment-blocked before implementation. The protocol prohibited edits without a RevertedFiles allow-list. The required final restore command ran and correctly reported that no baseline state existed (Restored=False). This does not validate or invalidate the proposed mechanism.

Inline self-review: 0 findings; there was no code diff.

Captured diff:

Full candidate narrative: ../try-fix-2/content.md

Final Comparison

Neither candidate produced an implementable or empirically tested alternative because the mandatory baseline script rejected the pre-existing dirty tracked reviewer-infrastructure overlay before either attempt could edit code. Both candidates are therefore Blocked, not Pass or Fail; there is no passing alternative to rank against the PR fix in STEP 5b.

The two bounded mechanisms remain distinct:

  1. Candidate 1 is Shell-specific and explicitly bridges known structural types.
  2. Candidate 2 is generic but splits transparent non-IView frontier projection from typed IView collection.

The existing PR remains the only empirically validated implementation in this phase: the prior gate showed all 7 HandlerLifeCycleTests passing with the PR fix and the new regression failing without it.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current description still claims an iOS ShellRenderer.DisconnectHandler() change that is absent from the submitted HEAD, while the title omits the Android and Windows BlazorWebView teardown work that is present.

Recommended title

[Core/Android/Windows] Shell and BlazorWebView: Complete handler teardown

Recommended description

### Issue Details

`DisconnectHandlers()` does not reach pages hosted inside a `Shell` tab when traversal encounters structural nodes such as `ShellItem` and `ShellSection`. When an application replaces `Window.Page`, handlers beneath the old Shell can remain connected, retaining native-resource-backed controls such as `BlazorWebView`, `WebView`, `HybridWebView`, and `GraphicsView`.

For `BlazorWebView`, failing to reach `BlazorWebViewHandler.DisconnectHandler()` means `WebViewManager.DisposeAsync()` is never started. The manager, native web view, and rendered Blazor component tree can therefore remain reachable across login flows, onboarding transitions, or full app resets, causing repeated memory growth.

### Root Cause

Two independent gaps are addressed:

1. **Shared Shell traversal:** The flat-list helper recursed into visual children only while the current element was an `IView`. `ShellItem` and `ShellSection` implement `IVisualTreeElement` but not `IView`, so traversal stopped before reaching the hosted `ContentPage` and its controls.
2. **Android and Windows native teardown:** Once traversal reaches `BlazorWebView`, Android also needs to detach and destroy its native `WebView`, and Windows needs to close its native WebView2 control. Those per-instance cleanup steps were incomplete.

### Description of Change

#### Core — all platforms

The `DisconnectHandlers()` traversal now treats collection and traversal separately:

- Add an element to the disconnect list only when it implements `IView`.
- Continue through its visual children whenever it implements `IVisualTreeElement`, including non-`IView` Shell structural nodes.
- Preserve `HandlerDisconnectPolicy.Manual` subtree pruning and the existing leaf-to-root disconnect order.

This lets traversal cross `ShellItem` and `ShellSection` without trying to disconnect them, then reach and disconnect their real `IView` descendants.

#### Android — `BlazorWebView`

The handler now retains the native WebView until Blazor disposal completes, then:

- Clears `WebViewClient` and `WebChromeClient`.
- Detaches the WebView from its parent.
- Removes its child views and calls `Destroy()`.
- Disposes the captured clients.

Blocking disposal performs cleanup synchronously after disposal. The default fire-and-forget path chains native cleanup after the disposal task and logs task failures, avoiding a synchronous UI-thread wait. If no `WebViewManager` was created, native cleanup runs immediately.

#### Windows — `BlazorWebView`

The handler now closes WebView2 after Blazor disposal completes. A shared guarded `CloseWebView2` helper is used by both per-instance disconnect and `Window.Destroying`, checks that `CoreWebView2` was initialized, and tolerates the other teardown path having already closed the control. Fire-and-forget disposal and close failures are logged.

The current submitted HEAD contains no iOS-specific `ShellRenderer.DisconnectHandler()` change. iOS and Mac Catalyst benefit from the shared Core traversal fix.

### Tests

`DisconnectHandlersReachesPageInsideShell` constructs:

`Shell -> ShellItem -> ShellSection -> ShellContent -> ContentPage -> Button`

It verifies that calling `shell.DisconnectHandlers()` clears the handlers for the Shell, hosted page, and nested control.

### Platform Impact and Validation

- [x] iOS — shared Shell traversal
- [x] Mac Catalyst — shared Shell traversal
- [x] Android — shared traversal plus native `BlazorWebView` cleanup
- [x] Windows — shared traversal plus native `BlazorWebView` cleanup

The Android cleanup was exercised with the reported leak-probe scenario. The Windows native teardown path was code-reviewed but was not separately verified in a Windows test environment.

### Issues Fixed

Fixes https://github.com/dotnet/maui/issues/36584

### Before/After Recordings

| Platform | Before | After |
|---|---|---|
| Mac | <video src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb"> | <video src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404"> |
| iOS | <video src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb"> | <video src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b"> |
| Windows | <video src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0"> | <video src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2"> |
| Android | <video src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1"> | <video src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d"> |

🏁 Report — Final Recommendation

✅ Final Recommendation: APPROVE

Winning candidate

Winner: pr

The submitted PR is the only implemented candidate with direct regression evidence. Its Shell traversal test fails without the fix and passes with the fix, with all seven filtered HandlerLifeCycleTests passing. The expert reviewer found no actionable file:line issue, and the mechanical regression cross-reference found no overlap with recent labeled bug fixes.

pr-plus-reviewer is source-equivalent to pr because the expert review identified no improvement to apply. The raw PR wins the tie: selecting a no-op derivative would incorrectly imply that the submitted code needs changes. Both STEP 5a alternatives were blocked before implementation and testing, so neither supplies code or evidence that can displace the validated PR.

Candidate comparison

Rank Candidate Implementation Validation Expert/regression assessment Outcome
1 pr Submitted five-file fix Gate passed: regression fails without fix; 7/7 filtered tests pass with fix; red full CI is baseline-matched No actionable expert finding; no mechanical regression overlap Winner
2 pr-plus-reviewer Identical to pr; empty reviewer patch Not rerun because no source refinement exists; inherits no separate result No reviewer improvement to distinguish it from pr Equivalent, not a better candidate
3 try-fix-2 Proposed generic non-IView frontier projection; no code produced Blocked before tests Mechanically distinct design, but unimplemented and unproven Lower confidence
4 try-fix-1 Proposed Shell-specific structural enumeration; no code produced Blocked before tests Unimplemented, unproven, and more tightly coupled to current Shell node types Lowest confidence

Technical comparison

The PR's shared traversal separates collection from traversal: only IView instances enter the disconnect list, while every IVisualTreeElement remains traversable. This directly covers the general failure mechanism without hard-coding Shell types. Manual disconnect policy still prunes a subtree, and the existing reverse-order disconnect behavior is preserved.

The Android and Windows changes defer native web-view destruction/closure until Blazor manager disposal completes, avoiding synchronous UI-thread blocking while completing native cleanup. The expert review found the disposal-before-native-teardown ordering and repeated Windows close handling sound.

try-fix-1 would bridge known Shell nodes explicitly, which is narrower and more brittle as Shell structure evolves. try-fix-2 is conceptually generic, but splitting frontier projection from typed recursion adds machinery without demonstrated correctness or a passing test. Since both candidates have empty diffs and no test result, their designs cannot outrank working, Gate-proven code.

CI and evidence qualification

Anonymous check retrieval found the current head's maui-pr build 1590515 failed. The latest inflight/current baseline build 1590052 fails with the same CS1061 errors at unchanged src/BlazorWebView/src/Maui/iOS/BlazorWebViewHandler.iOS.cs:322 for iOS and Mac Catalyst; the pack-stage missing-native-artifact error is downstream of those failed builds. The red checks are therefore pre-existing and PR-unrelated, so they do not displace the raw PR winner, although confidence remains capped at low.

The trusted Gate directly verifies the reported regression, and the expert found no code-level error or discussion item. No full suite or duplicate Gate run was performed.


📱 UI Tests — Button,Label,Layout

Detected UI test categories: Button,Label,Layout

⚠️ Deep UI tests — The build failed to compile for 3 categories (Button, Label, Layout), so those deep UI tests could not run. The compiler reported: error CS1061: 'BlazorWebViewHandler' does not contain a definition for 'Handler' and no accessible extension method 'Handler' accepting a first argument of type 'BlazorWebViewHandler' could be found (are you missing a using directive or an …. The cause is undetermined: the diagnostic is reported in unchanged file src/BlazorWebView/src/Maui/iOS/BlazorWebViewHandler.iOS.cs, but a PR API/signature change can break an unchanged consumer. Compare the same build against the reviewed base before attributing it; inspect build-output.log, then re-comment /review after the build issue is resolved.


🧭 Next Steps — review latest findings

No alternative fix was selected for this run. Review the session findings and CI results before merging.

@MauiBot MauiBot added s/agent-approved AI agent recommends approval - PR fix is correct and optimal s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates and removed s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-review-in-progress AI review is currently running for this PR labels Sep 10, 2026
@kubaflo
kubaflo merged commit c440c05 into dotnet:inflight/current Sep 10, 2026
4 of 12 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR11 milestone Sep 10, 2026
@MauiBot MauiBot mentioned this pull request Sep 10, 2026
kubaflo pushed a commit that referenced this pull request Sep 11, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Sep 15, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Sep 18, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Sep 21, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Sep 27, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Sep 27, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Oct 3, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Oct 3, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Oct 6, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Oct 6, 2026
…ctHandlers() (#38022)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Issue Details

DisconnectHandlers() never reaches pages hosted inside a Shell tab,
causing BlazorWebView (and other native-resource-backed controls like
WebView , HybridWebView , and GraphicsView ) to leak permanently once
Window.Page is replaced.
 
When an application sets Window.Page = new Shell(...) and that Shell
hosts a page containing a BlazorWebView , and later replaces Window.Page
with a different page (a common pattern during login flows,
onboarding-to-main-app transitions, or full app resets), the old Shell's
visual tree is expected to be fully disconnected so its handlers — and
the native resources they own — can be released and garbage collected.
Instead, the teardown silently stops partway through the tree, so
BlazorWebViewHandler.DisconnectHandler() is never invoked.
 
This is the only code path that starts WebViewManager.DisposeAsync() ,
so the WebViewManager , the native platform web view, and the entire
rendered Blazor component tree are never disposed. Repeating this
pattern (e.g., navigating in and out of a Shell-hosted BlazorWebView
screen multiple times) causes unbounded memory growth and can eventually
crash the app.

### Root cause

The issue stems from two independent defects that both had to be fixed
to fully resolve the leak.
 
1. Traversal gap (Core, all platforms). The internal tree-traversal
helper that builds a flat list of every view in the visual tree, so
their handlers can be safely disconnected afterward, only recursed into
an element's visual children when the current element was itself an
IView . ShellItem and ShellSection — the structural nodes Shell uses to
organize its tabs — implement IVisualTreeElement (so they expose child
elements) but do not implement IView (they have no handler of their own
to disconnect). Because traversal was gated on is IView , the walk
stopped dead as soon as it reached a ShellItem / ShellSection , and
everything nested beneath it — the hosted ContentPage and any controls
inside it, including BlazorWebView — was never visited and consequently
never had its handler disconnected. This was a latent gap present since
the disconnect traversal was first introduced; it went unnoticed because
most existing call sites operate on already-homogeneous IView trees, and
the one call site that walks through non- IView structural nodes — a
Shell being torn down — produces no crash or visible symptom, only a
silent, memory-profiler-visible leak.
 
2. Incomplete native teardown (Android and Windows). Even once traversal
correctly reached BlazorWebView and called its handler's disconnect
method, each platform's handler implementation still had to release its
own native resources — and two platforms did not do this fully:
 
• Android: the disconnect path never called Destroy() on the native
WebView , never detached it from its parent view group, and never
cleared its WebViewClient / WebChromeClient — all steps that MAUI's own
non-Blazor WebView handler already performs, and that Android's own API
docs require after removing a WebView from the view hierarchy.
• Windows: the disconnect path disposed the managed WebView manager but
never called .Close() on the native WebView2 control; that call was only
wired to app-shutdown, not to per-instance disconnect.

These two gaps predate and are independent of the traversal bug — they
only became reachable/observable once the traversal fix let the
disconnect logic actually get called.

### Solution description

Traversal fix (Core). The fix separates two responsibilities that had
been incorrectly conflated: "should this element be collected for
disconnection" and "should traversal continue past this element." The
traversal now adds an element to the flat list only if that element is
IView (preserving the original disconnect behavior for real views), but
unconditionally recurses into its visual children regardless of whether
the current element itself is an IView . This means structural, non-
IView nodes like ShellItem / ShellSection are still traversed through —
just not added to the disconnect list themselves — so traversal can
reach the real IView descendants nested beneath them and disconnect
their handlers as intended. Because this change is confined to shared,
platform-agnostic traversal logic with no platform-specific
conditionals, it uniformly fixes reachability for every control affected
by the same pattern.
 
Platform teardown fixes (Android and Windows). With the disconnect path
now reliably reached, each platform's handler was updated to fully
release native resources on disconnect:
 
• Android: the handler now performs the same teardown sequence as the
Core WebView handler — clearing WebViewClient / WebChromeClient ,
detaching the WebView from its parent, removing all views, and calling
Destroy() . Since Blazor's JS-driven component disposal needs the native
WebView to stay alive until its async disposal completes, the destroy
step is deferred as a continuation on the disposal task (or run
synchronously when blocking disposal is configured), guaranteeing native
cleanup runs exactly once, after disposal finishes.
• Windows: the handler now unconditionally calls .Close() on the native
WebView2 control as part of disconnect, rather than relying solely on
app-shutdown teardown, so the control is released as soon as the
BlazorWebView is disconnected.

• iOS teardown fix (Shell renderer): Beyond the Core traversal fix and
the Android/Windows  BlazorWebView  teardown, this PR also updates
 ShellRenderer.DisconnectHandler()  on iOS. Previously this method was
empty, so when a Shell was disconnected, the currently-active
 ShellItemRenderer  (and everything it hosts, including any
 BlazorWebView ) was never disconnected or disposed on iOS, and the
 Element / Handler  back-references were never cleared. The fix now:
unsubscribes from  Element.PropertyChanged , disconnects and disposes
the current  IShellItemRenderer  (removing its view from the superview
and its view controller from the parent controller), disposes the
 ShellRenderer  itself, clears the  Element 's  Handler  reference (if
still pointing at this renderer), and nulls out
 Element / _mauiContext . This closes the same class of leak on iOS that
the Core traversal fix closes for Android/Windows, and is required for
the fix to be complete across all four validated platforms.
 
Together, these changes ensure the visual tree is walked correctly,
disconnect logic is invoked for every affected control, and each
platform's handler fully releases its native resources — closing the
leak end-to-end. The Android fix has been empirically verified against
the customer's own leak-probe sample (no leak detected across repeated
passes); the Windows fix is code-reviewed but not yet verified on a
physical/emulated Windows environment.

Validated the behavior in the following platforms
 
- [x] iOS
- [x] Mac
- [x] Android
- [x] Windows
 
### Issues Fixed
  
Fixes #36584

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Mac|<video
src="https://github.com/user-attachments/assets/bda928c9-fdb4-4c86-8764-13f5bbc39ceb">
|<video
src="https://github.com/user-attachments/assets/84fae28d-f1bd-4d0d-96cd-e47704466404">|
|iOS|<video
src="https://github.com/user-attachments/assets/f5f13bfb-d931-45c6-b961-059112293edb">|<video
src="https://github.com/user-attachments/assets/b896af6d-a3b5-42e2-bcfe-6bf55b6f096b">|
|Windows|<video
src="https://github.com/user-attachments/assets/6ae2d458-4696-4d8f-b1c8-306b64ca70d0">|<video
src="https://github.com/user-attachments/assets/1f5bbe52-a87b-4298-9d35-adbe340a7ef2">|
|Android|<video
src="https://github.com/user-attachments/assets/76277961-8419-45fa-8e4c-8c144bb8b3c1">|<video
src="https://github.com/user-attachments/assets/2b422959-0bc1-47f2-af9a-6472b6eb908d">|
kubaflo pushed a commit that referenced this pull request Oct 7, 2026
…g handler disconnection (#39005)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!


<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Root cause

The issue occurs because the CollectionView selection callback continues
after Window.Page is replaced with the L2 Shell. The page replacement
disconnects the existing CollectionView handler, which clears its
PlatformView. When the selection flow continues and updates
SelectedItem, UpdateVirtualSelection() attempts to access the handler's
ListViewBase after the PlatformView has already been cleared, resulting
in an InvalidOperationException.

### Solution description

The fix involves preserving the native ListViewBase instance received
from the selection-change event and using it throughout the selection
synchronization process. The handler's current PlatformView is also
checked before updating the item content controls. This prevents access
to a cleared platform view when the handler is disconnected during
selection processing while retaining the handler-disconnection behavior
introduced by PR #38022.

### Regression PR

PR #38022

Validated the behavior in the following platforms
 
- [x] Windows
- [ ] Mac
- [ ] Android
- [ ] iOS
 
### Issues Fixed
  
Fixes #38618

### Output  ScreenShot

|Platform|Before|After|
|--|--|--|
|Windows| <video
src="https://github.com/user-attachments/assets/b58de799-1698-4e46-94f2-8d78cc36c57b">|
<video
src="https://github.com/user-attachments/assets/434c9881-df2e-42b0-a0b6-de25b029fa22">|

---------
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 11, 2026
@github-actions github-actions Bot modified the milestones: .NET 10 SR11, .NET 10 SR12 Oct 21, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-blazor Blazor Hybrid / Desktop, BlazorWebView community ✨ Community Contribution partner/syncfusion Issues / PR's with Syncfusion collaboration platform/android platform/windows s/agent-approved AI agent recommends approval - PR fix is correct and optimal s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

iOS: DisconnectHandlers() never reaches pages inside a Shell — BlazorWebView/WebViewManager leak permanently when Window.Page is replaced

6 participants