Skip to content

Fix BlazorWebView root component subscriptions on disconnect - #39247

Merged
kubaflo merged 1 commit into
dotnet:mainfrom
sheiksyedm:sheiksyedm-blazorwebview-activity-leak
Oct 8, 2026
Merged

kubaflo merged 1 commit into
dotnet:mainfrom
sheiksyedm:sheiksyedm-blazorwebview-activity-leak

Conversation

@sheiksyedm

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!

Description of Change

BlazorWebViewHandler subscribes to RootComponents.CollectionChanged but does not unsubscribe when disconnected. When an Android Activity is recreated with a cached Window and page, the page-owned collection retains replaced handlers, their MauiContext, and the destroyed Activity.

This change adds shared cleanup that removes the subscription and releases the handler's collection reference without clearing the root components. Cleanup runs before platform teardown in the Android, iOS/MacCatalyst, Windows, and Tizen handlers.

The regression test verifies that disconnect removes the subscription, preserves the root component, and allows the handler to reconnect with exactly one subscription.

Validation

  • Reproduced in Android Sandbox after two Activity recreations: both replaced handlers remained subscribed and retained destroyed Activity contexts.
  • Repeated the same scenario with the fix: only the current handler remained subscribed, and both replaced handlers were collected.
  • Ran the full before/after verification gate: the regression test failed without the fix at Assert.Empty because the subscription remained, and passed with the fix.
  • MacCatalyst build passed with 0 warnings and 0 errors.
  • Broader Android tests reported 39 passed, 4 failed, and 4 skipped. The failing path-resolution and back-navigation tests also failed with the Android fix removed.

Other Activity retention remained visible in Sandbox. This change fixes the reported handler subscription path, not every possible Activity retention source. Windows and Tizen builds and Apple runtime tests were not run.

Fixes #39227

Unsubscribe before platform teardown and release the handler's collection reference without clearing the page-owned root components. Apply the shared cleanup across platform handlers so reconnecting can subscribe normally.

Reproduced dotnet#39227 on Android in Sandbox: two replaced handlers remained subscribed and retained destroyed Activity contexts. With the fix, only the current handler remains subscribed and replaced handlers are collected. Other Activity retention in Sandbox remains outside this subscription fix.

Add a device regression test for unsubscribe, component preservation, and reconnect. It fails before the fix and passes afterward. Existing broader Blazor test failures also reproduce without the Android fix.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 8, 2026 07:03
@github-actions

github-actions Bot commented Oct 8, 2026

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 -- 39247

Or

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

@dotnet-policy-service dotnet-policy-service Bot added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Oct 8, 2026
@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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The implementation appears sound, but cross-platform handler CI is still pending and several affected platforms lack runtime validation.

0 open findings

What changed in this PR

Fixes BlazorWebViewHandler retaining disconnected handlers through root-component event subscriptions.

Changes:

  • Unsubscribes and releases root-component collections during platform teardown.
  • Preserves root components across disconnect/reconnect.
  • Adds a lifecycle regression test covering cleanup and resubscription.
File Description
BlazorWebViewHandler.cs Adds shared subscription cleanup.
BlazorWebViewHandler.Android.cs Runs cleanup during Android disconnect.
BlazorWebViewHandler.iOS.cs Runs cleanup for iOS and MacCatalyst.
BlazorWebViewHandler.Windows.cs Runs cleanup during Windows disconnect.
BlazorWebViewHandler.Tizen.cs Runs cleanup during Tizen disconnect.
BlazorWebViewTests.Lifecycle.cs Verifies unsubscribe, preservation, and reconnect behavior.

🧠 Review effort: Balanced


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

@sheiksyedm sheiksyedm added the community ✨ Community Contribution label Oct 8, 2026
@kubaflo

This comment has been minimized.

@kubaflo

kubaflo commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

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

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

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15610652 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@sheiksyedm sheiksyedm added the area-blazor Blazor Hybrid / Desktop, BlazorWebView label Oct 8, 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

@sheiksyedm — new AI review results are available based on commit bea568d.

Gate Passed Confidence Low Platform Android


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

Gate Result: ✅ PASSED

Platform: ANDROID · Base: main · Merge base: b926f057

Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 BlazorWebViewLifecycleTests (DisconnectUnsubscribesRootComponentsWithoutClearingThem) Category=BlazorWebView ✅ FAIL — 493s ✅ PASS — 381s
🔴 Without fix — 📱 BlazorWebViewLifecycleTests (DisconnectUnsubscribesRootComponentsWithoutClearingThem): FAIL ✅ · 493s

(no coded error found; showing last 1200 chars)

8272
          },
          "target": {
            "kind": "emulator",
            "name": "sdk_gphone_x86_64",
            "identifier": "emulator-5554",
            "operatingSystem": "Android",
            "operatingSystemVersion": "11",
            "apiLevel": 30,
            "architecture": "x86_64",
            "supportedArchitectures": [
              "x86_64",
              "x86",
              "arm64-v8a",
              "armeabi-v7a",
              "armeabi"
            ],
            "manufacturer": "Google",
            "model": "sdk_gphone_x86_64",
            "productName": "sdk_gphone_x86_64",
            "buildFingerprint": "google/sdk_gphone_x86_64/generic_x86_64_arm64:11/RSR1.201211.001/7027799:user/release-keys",
            "cpuModel": "0",
            "cpuMaxFrequencyHertz": 2000,
            "totalMemoryBytes": 2077544448
          }
        }
      }
      <<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.mauiblazorwebview.devicetests'..
info: Successfully uninstalled com.microsoft.maui.mauiblazorwebview.devicetests
XHarness exit code: 1 (TESTS_FAILED)
  Passed: 0
  Failed: 1
  Skipped: 0
  Total: 1
  Tests completed with exit code: 1
🟢 With fix — 📱 BlazorWebViewLifecycleTests (DisconnectUnsubscribesRootComponentsWithoutClearingThem): PASS ✅ · 381s

(no coded error found; showing last 1200 chars)

MemoryBytes": 8322998272
          },
          "target": {
            "kind": "emulator",
            "name": "sdk_gphone_x86_64",
            "identifier": "emulator-5554",
            "operatingSystem": "Android",
            "operatingSystemVersion": "11",
            "apiLevel": 30,
            "architecture": "x86_64",
            "supportedArchitectures": [
              "x86_64",
              "x86",
              "arm64-v8a",
              "armeabi-v7a",
              "armeabi"
            ],
            "manufacturer": "Google",
            "model": "sdk_gphone_x86_64",
            "productName": "sdk_gphone_x86_64",
            "buildFingerprint": "google/sdk_gphone_x86_64/generic_x86_64_arm64:11/RSR1.201211.001/7027799:user/release-keys",
            "cpuModel": "0",
            "cpuMaxFrequencyHertz": 2000,
            "totalMemoryBytes": 2077544448
          }
        }
      }
      <<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.mauiblazorwebview.devicetests'..
info: Successfully uninstalled com.microsoft.maui.mauiblazorwebview.devicetests
XHarness exit code: 0
  Passed: 1
  Failed: 0
  Skipped: 0
  Total: 1
  Tests completed successfully
📁 Fix files reverted (5 files)
  • src/BlazorWebView/src/Maui/Android/BlazorWebViewHandler.Android.cs
  • src/BlazorWebView/src/Maui/BlazorWebViewHandler.cs
  • src/BlazorWebView/src/Maui/Tizen/BlazorWebViewHandler.Tizen.cs
  • src/BlazorWebView/src/Maui/Windows/BlazorWebViewHandler.Windows.cs
  • src/BlazorWebView/src/Maui/iOS/BlazorWebViewHandler.iOS.cs

📋 Pre-Flight — Context & Validation

Pre-Flight Context

Snapshot

  • PR: #39247, “Fix BlazorWebView root component subscriptions on disconnect”
  • Submitted head: bea568d89e92c1201a318573dd554e33e95f4871
  • Base: main at b926f05713b0d1843f8f3bef28b025c6242f1d3c
  • Scope: One commit, six changed files, 77 additions.
  • Linked report: #39227, labeled verified/triaged for Android and Blazor.
  • This is context gathering only, not an exhaustive code review or recommendation.

Reported problem

On Android Activity recreation, an application can retain a cached Window, page, and BlazorWebView while replacing its handler. MapRootComponents assigns the view-owned RootComponentsCollection to the handler and subscribes OnRootComponentsCollectionChanged to CollectionChanged. Before this PR, platform disconnection did not remove that subscription.

The reported retention chain is:

Application/Window/Page/BlazorWebView
→ RootComponentsCollection
→ CollectionChanged delegate
→ old BlazorWebViewHandler
→ MauiContext
→ finished Activity

The issue reports one retained Activity per recreation, including a six-launch result where all six Activities remained alive. Its workaround manually removed the old handler’s event delegate. A triage comment reports reproduction on Android with .NET MAUI 10.0.110; the original reproduction describes packages at 9.0.120. The external reproduction repository and attached image were not inspected, so their detailed implementation and evidence remain unknown.

Changed mechanism

The immutable submitted diff makes these changes:

File Change
src/BlazorWebView/src/Maui/BlazorWebViewHandler.cs Adds DisconnectRootComponents(), which removes OnRootComponentsCollectionChanged from the current collection and sets the handler’s private _rootComponents reference to null.
src/BlazorWebView/src/Maui/Android/BlazorWebViewHandler.Android.cs Calls the helper before back-button cleanup, StopLoading, WebView manager disposal, and client disposal.
src/BlazorWebView/src/Maui/iOS/BlazorWebViewHandler.iOS.cs Calls the helper before stopping the WKWebView and disposing its manager. This source is shared by iOS and Mac Catalyst.
src/BlazorWebView/src/Maui/Windows/BlazorWebViewHandler.Windows.cs Calls the helper before disposing the WebView2 manager.
src/BlazorWebView/src/Maui/Tizen/BlazorWebViewHandler.Tizen.cs Calls the helper before removing Tizen events, invoking base disconnection, and removing the handler-table entry.
src/BlazorWebView/tests/DeviceTests/Elements/BlazorWebViewTests.Lifecycle.cs Adds a device regression test for unsubscribe, component preservation, and reconnect.

BlazorWebView constructs and owns a single getter-only RootComponentsCollection. The existing handler property setter clears a previously assigned collection before unsubscribing, so using that setter during disconnect would remove application root components. The new helper deliberately unsubscribes without clearing the view-owned collection.

On reconnection, SetVirtualView causes the RootComponents mapper to assign the collection again and subscribe the handler again. The helper is null-guarded, making repeated cleanup a no-op after the first disconnection.

Regression-test behavior

The new device test:

  • Creates a BlazorWebView with one NoOpComponent.
  • Omits HostPage, intentionally preventing WebView manager startup so event cleanup is isolated from manager disposal.
  • Uses reflection over ObservableCollection<RootComponent>.CollectionChanged to count delegates targeting BlazorWebViewHandler.
  • Verifies one initial handler subscription.
  • Disconnects and verifies no handler subscription remains.
  • Verifies the root component was not removed.
  • Reconnects the same handler and verifies exactly one subscription targeting that handler and the same preserved component.
  • Disconnects again in finally.

The provided Gate result is authoritative for this pre-flight context: the regression test fails without the fix and passes with it; Gate must not be rerun.

Platform-sensitive validation requirements

The requested validation platform is Android. Relevant behavioral validation should distinguish the direct subscription fix from broader lifecycle retention:

  • Recreate the Android Activity while retaining the page/BlazorWebView, then confirm replaced handlers no longer remain in the collection’s invocation list.
  • Confirm replaced handlers and their old MauiContext/Activity can be collected after disconnection.
  • Confirm the current handler remains subscribed exactly once after reconnection.
  • Confirm root components remain present and functional across disconnect/reconnect.
  • Exercise a real HostPage so Android WebView manager startup and asynchronous disposal occur alongside the new early unsubscribe.
  • Ensure collection changes after disconnection do not dispatch through the old handler or disposed manager.
  • Preserve existing Android back-callback, navigation, and WebView teardown behavior.

The PR description additionally reports:

  • Android Sandbox reproduction where two replaced handlers were retained before the fix and collected afterward.
  • A Mac Catalyst build with zero warnings/errors.
  • Broader Android results of 39 passed, 4 failed, and 4 skipped; the author states the four path-resolution/back-navigation failures also occur without this change.

Those statements were not independently reproduced here. PR comments show Azure Pipelines runs were started, but their completed outcomes are unknown.

Remaining uncertainties

  • The added test proves delegate removal and collection preservation, but does not directly prove handler, MauiContext, native WebView, or Activity garbage collection.
  • Because the test omits HostPage, it does not cover interaction with real WebView manager disposal or an Android Activity recreation.
  • Reflection depends on the current private event-field representation of ObservableCollection<T>.
  • The issue explicitly identifies a separate Android native WebView/Context retention path when the WebView is not destroyed; this PR does not claim to fix that or every Activity-retention source.
  • According to the PR description, Windows and Tizen builds and Apple runtime tests were not run; Mac Catalyst has build-only evidence.
  • Runtime behavior on iOS, Mac Catalyst, Windows, and Tizen therefore remains unverified in the available context.
  • The exact resolved platform set behind $(MauiDeviceTestsPlatforms) was not available from the files read; Android is explicitly required for this validation.
  • Current full CI status, detailed results for the four broader Android failures, and the separate expert-review findings are unknown.

🔬 Code Review — Deep Analysis

Code Review — PR #39247

Independent Assessment

What this changes:
The PR introduces a shared DisconnectRootComponents() helper in BlazorWebViewHandler that unsubscribes OnRootComponentsCollectionChanged and nulls the handler-held _rootComponents reference without clearing the view-owned collection. Each platform DisconnectHandler (Android/iOS/Windows/Tizen) now calls this helper before the rest of teardown. A new lifecycle device test verifies unsubscribe-on-disconnect, root-component preservation, and resubscribe-on-reconnect.

Inferred motivation:
Prevent retention of disconnected handlers (and associated Android Activity context chains) through RootComponentsCollection.CollectionChanged delegates during handler replacement/recreation.

Approach soundness:
Yes. The helper avoids using the RootComponents setter (which would clear components) and performs the minimum lifecycle-symmetric cleanup required for disconnect.

Reconciliation with PR Narrative

Author claims: handler subscription leak on disconnect; fix unsubscribes without clearing components; Android repro validated; regression test fails without fix and passes with fix.
Agreement/disagreement: Code-level behavior matches the claim. The new test directly validates the subscription cleanup mechanism and preservation semantics.

Prior Review Reconciliation

Prior ❌ Error Finding Source Status Evidence
None N/A N/A Top-level reviews, inline comments, and issue comments contain no unresolved ❌ error-level findings for this PR.

Blast Radius Assessment

  • Runs for all instances: Yes for all BlazorWebViewHandler disconnects on Android/iOS/Windows/Tizen.
  • Startup impact: No (disconnect path only).
  • Static/shared state: No new static/shared state introduced by this PR.

CI Status

  • Required-check result: undetermined/pending with active failure signal (derived from check-runs API because gh pr checks --required was unavailable without auth in this environment).
  • Observed checks at PR head:
    • maui-pr-devicetests (net10.0 Android CoreCLR Helix Tests Run DeviceTests Android (CoreCLR)) → completed/failure
    • maui-pr-devicetests (net10.0 Windows Helix Tests Run DeviceTests Windows) → in_progress
  • Classification: undetermined (not enough evidence here to attribute failure to PR code vs infrastructure/test flake).
  • Action taken: confidence capped low; no LGTM.

Findings

No validated code-level actionable defects were found in the submitted diff after full-file/context review.

Failure-Mode Probing

  • Disconnect/reconnect on same view instance: subscription is removed on disconnect and re-added via mapper on SetVirtualView; test covers this and prevents duplicate stale handler subscriptions.
  • Root component preservation: helper unsubscribes without calling the setter path that clears prior collection; test verifies component instance is preserved across disconnect/reconnect.
  • Platform lifecycle teardown ordering: helper is invoked before platform-specific disposal/teardown in all changed handlers, preventing stale collection callbacks from targeting disconnected handlers.
  • Null/default paths: helper is null-guarded and idempotent when _rootComponents is already null.

External Output Contract

Not applicable (this PR does not add/change regex or string classification against external tool output).

Trim/AOT Evidence Chain

Not applicable (no changes to trim/AOT annotations, suppressions, reflection guards, or dynamic-code attributes).

Verdict: NEEDS_DISCUSSION

Confidence: low

Summary:
The implementation and regression test for root-component unsubscription are mechanically sound and align with the reported leak mechanism. However, CI is not in a merge-clear state (one relevant device-test failure plus pending required execution), and failure attribution is unresolved in this pass. With undetermined CI coverage, recommendation remains NEEDS_DISCUSSION rather than approval.


🛠️ Try-Fix — Analysis & Comparison

Alternative generation: not requested

Evidence-first mode intentionally omits routine Try-Fix attempts. This is not a failed
attempt, a completed alternative search, or evidence that alternatives have no value.
The expert review may still produce one evidence-backed PR refinement.


🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Phase Status

Phase Status Notes
Pre-Flight ✅ COMPLETE Trusted evidence-first context consumed
Expert Review ⚠️ NEEDS_DISCUSSION (low) No code-level findings; broader CI evidence is unresolved
Gate ✅ PASSED Android regression test failed without the fix and passed with it
Try-Fix not requested Intentionally omitted by evidence-first mode
Refinement ⏭️ NOT GENERATED No concrete actionable defect or unresolved behavioral mechanism met the evidence threshold
Report ✅ COMPLETE Raw pr assessed as the sole real candidate

Code Review and Candidate Comparison

Candidate Targeted validation Expert assessment Comparative result
pr ✅ PASSED The subscription cleanup is mechanically sound and no actionable code defect was found. Broader CI remained unresolved: an Android CoreCLR device-test check was failing while a Windows device-test check was still in progress, with no failure attribution available. Winner and sole candidate, but not demonstrated merge-ready while that CI evidence remains unresolved

No pr-plus-reviewer refinement was implemented because the expert review found no source- or test-backed defect to correct. Routine alternative generation was not requested; this is not an exhausted or failed candidate search.

Summary

The submitted PR is the strongest and only real candidate. Its focused Android Gate proves the new lifecycle test fails without the fix and passes with it, and the expert review found no blocking implementation error. Approval is nevertheless vetoed by the expert NEEDS_DISCUSSION verdict: current broader CI includes a failure and a pending run whose relevance has not been established. No source change is identified by this review, but that evidence must be resolved or classified before approval.

Root Cause

BlazorWebViewHandler retained the view-owned RootComponentsCollection and remained registered with its CollectionChanged event after handler disconnection. A cached view could therefore retain replaced handlers and their MauiContext, including a destroyed Android Activity.

Fix Quality

The shared cleanup removes the event handler and releases the handler-owned collection reference without invoking the existing setter path that clears application root components. Calling it before platform teardown on Android, iOS/Mac Catalyst, Windows, and Tizen is lifecycle-symmetric and idempotent. The regression test covers unsubscribe, component preservation, and a single subscription after reconnect, and the Gate validates that behavior on Android. The remaining blocker is evidence quality outside that focused Gate, not a demonstrated defect in the submitted code.


🧭 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-changes-requested AI agent recommends changes - found a better alternative or issues 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) and removed s/agent-review-in-progress AI review is currently running for this PR labels Oct 8, 2026
@kubaflo
kubaflo merged commit d356b4b into dotnet:main Oct 8, 2026
193 of 211 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR12 milestone Oct 8, 2026
This was referenced Nov 1, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 8, 2026

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — bea568d8 Deployed Oct 8, 2026 by sheiksyedm via conclusion #2280
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 s/agent-changes-requested AI agent recommends changes - found a better alternative or issues 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

4 participants