Repository navigation
[Windows] Fix GraphicsView crash during repeated drawing - #37419
Conversation
Clear the Win2D drawing session after each GraphicsView draw callback so the persistent canvas cannot retain a disposed native session. Cover repeated invalidation with a Windows device test. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 01dac3d5-7cea-4af6-ba68-fdc87f9ceb54
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37419Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37419" |
|
Azure Pipelines: Successfully started running 1 pipeline(s). There may be pipelines that require an authorized user to comment /azp run to run. |
There was a problem hiding this comment.
Pull request overview
This PR fixes a Windows-specific crash in Win2D-backed GraphicsView drawing by ensuring the callback-scoped CanvasDrawingSession is not retained past the Win2D draw callback lifetime, preventing later use of a disposed native session during repeated redraws and shutdown.
Changes:
- Clear the Win2D
CanvasDrawingSessionreference (_canvas.Session) after each draw callback completes (even if canvas state reset throws). - Add a Windows device test that performs repeated invalidation/draw cycles and asserts the drawing session is released after every draw.
Show a summary per file
| File | Description |
|---|---|
| src/Graphics/src/Graphics/Platforms/Windows/PlatformGraphicsView.cs | Ensures the Win2D drawing session reference is cleared in a nested finally, preventing stale/disposed session reuse. |
| src/Core/tests/DeviceTests/Handlers/GraphicsView/GraphicsViewHandlerTests.Windows.cs | Adds a Windows device test validating the drawing session is released after repeated draw callbacks. |
Review details
- Files reviewed: 2/2 changed files
- Comments generated: 0
- Review effort level: Lite
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 4 findings
See inline comments for details.
| } | ||
| finally | ||
| { | ||
| _canvas.Session = null; |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
💡 Suggestion — Image/Graphics (Windows) resource retention: Clearing _canvas.Session releases the per-frame CanvasDrawingSession, but PlatformCanvas also caches _patternContext and _effectContext (CanvasRenderTarget instances constructed from that session, see GetOrCreatePatternContext/GetOrCreateEffectContext). Those are only disposed when the requested size changes, are never disposed on UserControl_Unloaded, and the _canvas field is readonly and lives for the lifetime of the view — so for drawables that use shadow, blur, or pattern fills the Win2D device resources are still pinned after the view is unloaded. Concrete scenario: a GraphicsView whose drawable calls SetShadow/SetBlur is navigated away from; the session is now released but the effect render target keeps the device surface alive. Consider disposing the cached render targets/effects at the same point (or from UserControl_Unloaded) so the release is complete.
|
|
||
| public void Draw(ICanvas canvas, RectF dirtyRect) | ||
| { | ||
| _nextDraw.TrySetResult(Assert.IsType<W2DCanvas>(canvas)); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
Assert.IsType<W2DCanvas>(canvas) runs inside IDrawable.Draw, i.e. inside PlatformGraphicsView.OnDraw, which is invoked from Win2D's CanvasControl.Draw event on the UI thread. If the assertion fails, the XunitException propagates out of the draw callback into Win2D/WinUI rather than into the test, and — because TrySetResult is never reached — the awaiting side additionally blocks until the 5s WaitAsync timeout. The result is an unhandled-exception host crash or an opaque TimeoutException instead of a readable assertion failure. Capture the canvas (_nextDraw.TrySetResult(canvas as W2DCanvas) or store the raw ICanvas) and perform the type assertion on the awaiting side, where xunit can report it.
| async () => | ||
| { | ||
| var canvas = await drawable.NextDraw.WaitAsync(TimeSpan.FromSeconds(5)); | ||
| Assert.Null(canvas.Session); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
💡 Suggestion — regression test is not discriminating: The only assertion is Assert.Null(canvas.Session) observed after the draw completes. This passes both for the intended fix and for a regression in which _canvas.Session is never assigned at all (or OnDraw early-returns before assignment), which would silently break all Windows GraphicsView rendering while keeping this test green. Add a positive signal captured during the draw — e.g. have CapturingDrawable.Draw record ((W2DCanvas)canvas).Session is not null (or perform a real draw call) and assert that recorded flag alongside the post-draw null check — so the test can distinguish "session released" from "session never set".
| var canvas = await drawable.NextDraw.WaitAsync(TimeSpan.FromSeconds(5)); | ||
| Assert.Null(canvas.Session); | ||
|
|
||
| for (int i = 0; i < 100; i++) |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
💡 Suggestion — device-test runtime/flake budget: The loop repeats the identical Assert.Null(canvas.Session) 100 times, each with a 5s WaitAsync. Iterations 2..100 add no new signal for this fix (the session is cleared in a finally on every OnDraw), but they do add up to 100 invalidate/present round-trips on a contended Windows CI agent, and any single dropped/coalesced CanvasControl.Invalidate() turns into a 5s TimeoutException. If the intent is to catch cumulative retention, assert on that directly (e.g. a WeakReference to a previously captured session being collected, or a memory threshold) and drop the iteration count to a handful; otherwise 2–3 iterations are sufficient to prove per-frame release.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@jfversluis — new AI review results are available based on commit
7bcafd0.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ✅ PASSED
Platform: WINDOWS · Base: main · Merge base: 5d86a00a
| Test | Without Fix (expect FAIL) | With Fix (expect PASS) |
|---|---|---|
📱 GraphicsViewHandlerTests (GraphicsViewReleasesWin2DDrawingSessionsAfterRepeatedDrawing) Category=GraphicsView |
✅ FAIL — 376s | ✅ PASS — 288s |
🔴 Without fix — 📱 GraphicsViewHandlerTests (GraphicsViewReleasesWin2DDrawingSessionsAfterRepeatedDrawing): FAIL ✅ · 376s
(no coded error found; showing last 1200 chars)
ss the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Controls\src\Core\Controls.Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
Platform\Windows\TabbedPage\TabbedPageStyle.xaml(13,13): XamlCompiler warning WMC1510: Ensure the property path is trimming and AOT compatible by making use of 'Compiled Bindings (x:bind)' if possible or by specifying the 'x:DataType' directive with the respective binding data context and marking the type declaration with the 'WinRT.GeneratedBindableCustomProperty' attribute or the 'Microsoft.UI.Xaml.Data.Bindable' attribute. If you are unable to do either but can ensure the data type is attributed correctly, then you can also suppress the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Controls\src\Core\Controls.Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
0 Error(s)
Time Elapsed 00:04:51.43
Passed: 0
Failed: 1
Skipped: 0
Total: 1
Tests completed with exit code: 1
🟢 With fix — 📱 GraphicsViewHandlerTests (GraphicsViewReleasesWin2DDrawingSessionsAfterRepeatedDrawing): PASS ✅ · 288s
(no coded error found; showing last 1200 chars)
uppress the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Controls\src\Core\Controls.Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
Platform\Windows\TabbedPage\TabbedPageStyle.xaml(13,13): XamlCompiler warning WMC1510: Ensure the property path is trimming and AOT compatible by making use of 'Compiled Bindings (x:bind)' if possible or by specifying the 'x:DataType' directive with the respective binding data context and marking the type declaration with the 'WinRT.GeneratedBindableCustomProperty' attribute or the 'Microsoft.UI.Xaml.Data.Bindable' attribute. If you are unable to do either but can ensure the data type is attributed correctly, then you can also suppress the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Controls\src\Core\Controls.Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
0 Error(s)
Time Elapsed 00:04:33.08
Passed: 1
Failed: 0
Skipped: 0
Total: 1
Tests completed successfully
📁 Fix files reverted (1 files)
src/Graphics/src/Graphics/Platforms/Windows/PlatformGraphicsView.cs
📋 Pre-Flight — Context & Validation
PR #37419 Pre-Flight
Context
- PR: [Windows] Fix GraphicsView crash during repeated drawing
- Linked issue: #29418, a reproducible Windows crash (
0xc000027b) while rapidly pressing/moving over text drawn byGraphicsView, especially withManipulationMode.All, a custom font, and pointer-triggered redraws. - Base / review HEAD:
origin/mainat5d86a00a; materialized review commit8d256696. - Platform: Windows.
- Gate: Passed previously. The new regression test failed without the PR fix and passed with it. Do not repeat gate verification or modify
gate/content.md.
Existing Fix
The PR changes two files:
src/Graphics/src/Graphics/Platforms/Windows/PlatformGraphicsView.csOnDrawcurrently stores Win2D's callback-scopedCanvasDrawingSessionin the persistent_canvas.- The PR clears
_canvas.SessionafterResetState, using nestedfinallyblocks so both the session andPlatformGraphicsService.ThreadLocalCreatorare released even if reset throws.
src/Core/tests/DeviceTests/Handlers/GraphicsView/GraphicsViewHandlerTests.Windows.cs- Adds
GraphicsViewReleasesWin2DDrawingSessionsAfterRepeatedDrawing, which performs an initial draw and 100 invalidation cycles and asserts that the capturedW2DCanvas.Sessionis null after each callback.
- Adds
The root problem is lifetime mismatch: Win2D owns and disposes CanvasDrawingSession after each draw callback, while the persistent MAUI canvas retains the managed reference across callbacks and shutdown.
Bounded Validation
Use only the detected primary regression test:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Core -Platform windows -TestFilter "Category=GraphicsView" -IncludeClasses "Microsoft.Maui.DeviceTests.GraphicsViewHandlerTests" -IncludeMethods "GraphicsViewReleasesWin2DDrawingSessionsAfterRepeatedDrawing" -RebuildNo additional mandatory regression tests were supplied for STEP 5a. Do not run a full suite.
Candidate Constraints
- Each candidate must pursue a root-cause approach distinct from the PR fix and from earlier candidates.
- One implementation/test pass is allowed, plus at most one focused correction/retest.
- Use
EstablishBrokenBaseline.ps1exactly as required by thetry-fixskill, and restore it at the end. - Preserve all unrelated pre-existing worktree changes, particularly the modified review/test infrastructure under
.githubandeng. - Perform the
try-fixinline expert self-review; do not launch another reviewer.
🔬 Code Review — Deep Analysis
Expert Code Review — PR #37419
Independent Assessment
What this changes: The Windows PlatformGraphicsView keeps its reusable PlatformCanvas, but now clears the callback-owned Win2D CanvasDrawingSession after each draw. ResetState() runs first while the session remains valid, and nested cleanup releases both the session reference and PlatformGraphicsService.ThreadLocalCreator even when reset throws.
Inferred motivation: The persistent canvas previously retained a Win2D session after its draw callback ended, allowing later redraw or teardown paths to observe an already-disposed native object.
Findings
- No blocking correctness errors were found in the production fix.
⚠️ The test performsAssert.IsType<W2DCanvas>inside the Win2D callback. A type mismatch can escape into WinUI and leave the waiter to report an opaque timeout rather than the assertion.- 💡 The test should positively establish that the session was non-null during drawing as well as null afterward, so it cannot pass if session assignment is accidentally removed.
- 💡 One hundred invalidate/wait cycles add device-test runtime and coalescing-related flake exposure without materially increasing coverage of the per-callback
finally. - 💡 Clearing
Sessiondoes not dispose the persistent canvas's session-derived pattern/effect render targets. Drawables using patterns, shadows, or blur can retain those device resources until the view itself is collected.
The raw file-and-line comments are persisted in ../inline-findings.json.
Blast Radius and Failure-Mode Probing
- The production change is Windows-only and runs only for draw callbacks with a non-null drawable; startup and other platforms are unaffected.
- The canvas is private and retained by one view. All ordinary session consumers execute inside
OnDraw, before cleanup. - Reset ordering is correct: clearing the session before
ResetState()would bypassPlatformCanvas.StateRestoredrender-target restoration. - Drawable and reset exceptions now preserve cleanup. Handler unload/reload no longer leaves the callback-owned session rooted, although the separate pattern/effect caches remain a residual lifetime concern.
- The trusted gate establishes that the focused regression test fails without the fix and passes with it.
Verdict: LGTM
Confidence: medium
The submitted production fix is minimal, exception-safe, and directly addresses the verified lifetime mismatch. The findings are non-blocking but actionable: a consolidated reviewer candidate can strengthen the test and complete cleanup of session-derived cached resources without changing the core approach.
🛠️ Try-Fix — Analysis & Comparison
PR #37419 Alternative Fix Candidates
Candidate 1 — Per-Draw Canvas Ownership
Model: claude-opus-5
Result: Pass (first implementation/test pass; no correction needed)
Approach
Treat the canvas and all resources derived from Win2D's CanvasDrawingSession as callback-scoped. Instead of retaining one PlatformCanvas on PlatformGraphicsView, create and dispose a canvas for each OnDraw callback. Add PlatformCanvas.Dispose() to unwind state while the session is valid, detach the Win2D-owned session without disposing it, and dispose session-derived pattern/effect render targets and effects.
This differs from the PR's nested-finally cleanup: the PR retains a persistent canvas and nulls only its session reference, while this candidate changes the ownership model so neither the session nor session-derived resources can outlive the callback.
Files and Diff
src/Graphics/src/Graphics/Platforms/Windows/PlatformGraphicsView.cs(+27/-20)src/Graphics/src/Graphics/Platforms/Windows/PlatformCanvas.cs(+28)src/Graphics/src/Graphics/PublicAPI/net-windows/PublicAPI.Unshipped.txt(+1)src/Graphics/src/Graphics.Win2D/PublicAPI/net-windows/PublicAPI.Unshipped.txt(+1)- Existing regression test unchanged.
The exact diff is recorded in:
../try-fix-1/content.mdattempt-1/fix.diff
Key changes were removal of the persistent _canvas, using (var canvas = new PlatformCanvas()) inside OnDraw, and a public Dispose() override that resets state, clears _session, and disposes _patternContext, _effectContext, _shadowEffect, and _blurEffect.
Test Result
Command:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Core -Platform windows -TestFilter "Category=GraphicsView" -IncludeClasses "Microsoft.Maui.DeviceTests.GraphicsViewHandlerTests" -IncludeMethods "GraphicsViewReleasesWin2DDrawingSessionsAfterRepeatedDrawing" -RebuildScoped result: 1 passed, 0 failed, 0 skipped. The build and test passed on the first run against the broken baseline.
Analysis and Self-Review
The captured canvas has Session == null after every draw because it is disposed as the callback exits; no session-derived native object remains on a persistent canvas. Inline self-review recorded one moderate performance finding: per-draw canvases discard cross-frame pattern/effect render-target caches, potentially increasing allocations for shadow, blur, and pattern drawing. There were no critical or major findings.
Baseline restoration completed successfully. Full narrative and test excerpts are in ../try-fix-1/content.md; raw artifacts are in attempt-1/.
Candidate 2 — Stack-Scoped Drawing-Session Lease
Model: gpt-5.6-sol
Result: Pass (one source implementation and one successful bounded test; no source correction)
Approach
Keep the persistent canvas and its cross-frame caches, but represent Win2D's callback-owned session as a lexical borrow rather than ordinary mutable view state. A private readonly ref struct DrawingSessionLease assigns the session when constructed and clears it through pattern-based Dispose() at the end of the synchronous OnDraw frame. ResetState() still runs while the session is valid, and nested cleanup independently guarantees that the thread-local creator is cleared.
This differs from both earlier approaches:
- The PR manually clears
_canvas.Sessioninside the view's nestedfinally. - Candidate 1 scopes and disposes the entire canvas per callback, losing cross-frame caches.
- Candidate 2 scopes only the borrowed session, retains the persistent canvas, adds no public API, and allocates no per-draw heap object.
Files and Diff
Only src/Graphics/src/Graphics/Platforms/Windows/PlatformGraphicsView.cs changed (+25/-3); the regression test was unchanged.
@@
+using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.UI.Xaml;
@@
+ private readonly ref struct DrawingSessionLease
+ {
+ private readonly PlatformCanvas _canvas;
+
+ public DrawingSessionLease(PlatformCanvas canvas, CanvasDrawingSession session)
+ {
+ _canvas = canvas;
+ _canvas.Session = session;
+ }
+
+ public void Dispose()
+ {
+ _canvas.Session = null;
+ }
+ }
@@
+ using var drawingSession = new DrawingSessionLease(_canvas, args.DrawingSession);
PlatformGraphicsService.ThreadLocalCreator = sender;
try
{
- _canvas.Session = args.DrawingSession;
@@
finally
{
- _canvas.ResetState();
- PlatformGraphicsService.ThreadLocalCreator = null;
+ try
+ {
+ _canvas.ResetState();
+ }
+ finally
+ {
+ PlatformGraphicsService.ThreadLocalCreator = null;
+ }
}The exact diff is also recorded in attempt-2/fix.diff and ../try-fix-2/content.md.
Test Result
Command:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Core -Platform windows -TestFilter "Category=GraphicsView" -IncludeClasses "Microsoft.Maui.DeviceTests.GraphicsViewHandlerTests" -IncludeMethods "GraphicsViewReleasesWin2DDrawingSessionsAfterRepeatedDrawing" -RebuildThe initial invocation stopped during parameter binding because parking the unrelated dirty worktree also parked the locally enhanced required runner; no build or test ran. After materializing that runner without changing candidate source, the exact bounded command completed with 1 passed, 0 failed, 0 skipped.
Analysis and Self-Review
The stack-only lease cannot escape or be captured by asynchronous work. Compiler-generated cleanup clears the persistent canvas's session after all reset work, including exceptional paths, while preserving the canvas and its render-target/effect caches. Inline self-review was clean with 0 findings.
Baseline restoration completed successfully, with final HEAD and dirty status matching the pre-run snapshots. Full narrative and output are in ../try-fix-2/content.md; raw artifacts are in attempt-2/.
🏁 Report — Final Recommendation
⚠️ Final Recommendation: REQUEST CHANGES
Winner: pr-plus-reviewer
pr-plus-reviewer retains the submitted PR's correct, exception-safe drawing-session cleanup while completing the expert review's actionable improvements. Its focused Windows device test passed from the mandated candidate sandbox, and it improves both resource teardown and regression-test reliability without candidate 1's per-frame allocation cost or candidate 2's additional lease abstraction.
Comparative Ranking
| Rank | Candidate | Regression evidence | Assessment |
|---|---|---|---|
| 1 | pr-plus-reviewer |
PASS — 1 scoped test passed, 0 failed, 0 skipped | Best balance. Keeps the minimal nested-finally fix, releases device-bound pattern/effect caches on unload, proves the session existed during drawing, moves assertions out of the Win2D callback, and bounds redraw repetition. |
| 2 | pr |
PASS — trusted Gate fails without the fix and passes with it | Production fix is sound and the expert found no blocking error. Ranked below the winner because cached Win2D resources remain attached across unload, and the test can fail opaquely inside the callback, does not prove session assignment, and performs 100 unnecessary waits. |
| 3 | try-fix-2 |
PASS — 1 scoped test passed after a runner-only environment correction | The stack-scoped session lease preserves the persistent canvas and caches with no heap allocation or public API. It reaches essentially the same lifetime result as the simpler PR cleanup, adds a private ref struct abstraction, and does not address the cache-unload or test-quality findings. |
| 4 | try-fix-1 |
PASS — 1 scoped test passed on the first implementation run | Per-draw canvas ownership makes callback lifetime explicit and disposes all session-derived resources, but it adds public Dispose() overrides and recreates canvas/render-target state every frame. Its own review identified the resulting allocation/cache-churn risk in a graphics hot path. |
No candidate failed its focused regression test, so no failed candidate needed the mandatory lower ranking.
Expert Review Reconciliation
The sole MAUI expert review found the submitted session-reset ordering correct: ResetState() must run while the session is still available, and the nested finally reliably clears both the session and thread-local creator on exceptional paths. It reported no blocking production error, one test warning, and three suggestions. pr-plus-reviewer applies those findings in one patch and passed the required validation without a repair/retest loop.
The required focused test does not create pattern/effect caches, so their unload disposal is validated by code-path analysis rather than a dedicated runtime assertion. No additional test was run under the bounded execution contract.
Required Change
Use the persisted pr-plus-reviewer/reviewer.patch. The raw submitted PR is functionally correct, but it is not the winning candidate because the reviewer-enhanced version provides more complete unload cleanup and a safer, more discriminating regression test.
📱 UI Tests — Button,Label,Layout
Detected UI test categories: Button,Label,Layout
❌ Deep UI tests — 344 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 |
69/70 (1 skipped) ✓ | — |
Label |
91/95 (1 ❌, 3 skipped) | — |
Layout |
184/188 (4 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 — Label/Grid rapid-tap coordinates (1 test):
TapTwoPlacesQuicklyexercises TapGesture event ordering rather than GraphicsView drawing, and the first result matching the second tap's X is consistent with rapid-input flakiness outside the PR's Win2D session-cleanup change.
❌ Label — 1 failed test
TapTwoPlacesQuickly
First tap has unexpected X value
Assert.That(actual, Is.EqualTo(expected).Within(delta))
Expected: 179.0d +/- 1.5d
But was: 278.982666015625d
Off by: -99.982666015625d
at NUnit.Framework.Legacy.ClassicAssert.AssertDoublesAreEqual(Double expected, Double actual, Double delta, String message, Object[] args)
at NUnit.Framework.Legacy.ClassicAssert.AreEqual(Double expected, Double actual, Double delta, String message, Object[] args)
at Microsoft.Maui.TestCases.Tests.Issues.Issue16561.AssertCorrectTapLocation(String tapData, Single expectedX, Single expectedY, String which) in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue16561.cs:line 76
at Microsoft.Maui.TestCases.Tests.Issues.Issue16561.TapTwoPlacesQuickly() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue16561.cs:line 57
1) at NUnit.Framework.Legacy.ClassicAssert.AssertDoublesAreEqual(Double expected, Double actual, Double delta, String message, Object[] args)
at NUnit
...
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)
🧭 Next Steps — reviewer patch required (pr-plus-reviewer)
The reviewer-enhanced candidate won, so the submitted PR still needs those changes.
Why: The reviewer-enhanced PR preserves the submitted fix's correct session-reset ordering while releasing cached Win2D resources on unload and making the regression test safer, discriminating, and bounded. Its single required focused validation passed.
Apply PRAgent/pr-plus-reviewer/reviewer.patch from the CopilotLogs
artifact (or follow the report's Required submitted-PR change), push the update, and run
the review again.
<!-- 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! ### Description Fixes #29418. On Windows, `W2DGraphicsView` stored Win2D's callback-scoped `CanvasDrawingSession` on its persistent canvas. Win2D disposes that native session after the draw callback returns, but the stale managed reference remained available across repeated pointer-driven redraws and shutdown, leading to native access violations and heap corruption. This change clears the drawing session after canvas state has been reset. The nested cleanup guarantees the session and thread-local canvas owner are released even if state reset throws. @Kamalesh-Periyasamy, once the PR artifacts are available, could you please try them with your original application and let us know whether they resolve the crash? ### Tests - Added a Windows device test that performs an initial draw plus 100 explicit invalidation/draw cycles and verifies the drawing session is released after every callback. - Verified the test fails without the fix by observing the retained, already-disposed `CanvasDrawingSession`. - Core DeviceTests: 2,092 total, 1,981 passed, 111 skipped, 0 failed. - Ran the exact issue attachment twice for 120 seconds each with 3,848 presses and 38,480 pointer moves per run; both exited cleanly with code 0 and no correlated Windows application errors. - Also validated custom/default fonts, `ManipulationMode.All`/`None`, multiple views, redraw, resize, unload, and graceful shutdown. ### Video verification #### Before — original reported crash The issue author's original recording shows the attached app failing during pointer interaction: https://github.com/user-attachments/assets/eecd8e89-17c9-4764-b21e-9e6c15141fb4 #### After — fixed DLL under sustained pointer stress The exact attached application was rebuilt with an ABI-compatible fixed `Microsoft.Maui.Graphics.Win2D.WinUI.Desktop.dll`, then exercised with real `SendInput` pointer presses and moves for 120 seconds: https://github.com/user-attachments/assets/41a3e68c-e048-4d09-b677-aec1a9bc3af7 This recorded run delivered 11,622 presses and 116,220 pointer moves, then closed normally with exit code `0`. No correlated `Application Error` or `.NET Runtime` event was recorded. The native crash is intermittent: fresh recording attempts against the original DLL did not fail during the capture session, so the before clip above is the reporter's genuine original failure rather than a clean run being mislabeled or a crash being staged. The deterministic regression evidence is the baseline test retaining an already-disposed `CanvasDrawingSession`; the same test passes after this change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 01dac3d5-7cea-4af6-ba68-fdc87f9ceb54
<!-- 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! ### Description Fixes #29418. On Windows, `W2DGraphicsView` stored Win2D's callback-scoped `CanvasDrawingSession` on its persistent canvas. Win2D disposes that native session after the draw callback returns, but the stale managed reference remained available across repeated pointer-driven redraws and shutdown, leading to native access violations and heap corruption. This change clears the drawing session after canvas state has been reset. The nested cleanup guarantees the session and thread-local canvas owner are released even if state reset throws. @Kamalesh-Periyasamy, once the PR artifacts are available, could you please try them with your original application and let us know whether they resolve the crash? ### Tests - Added a Windows device test that performs an initial draw plus 100 explicit invalidation/draw cycles and verifies the drawing session is released after every callback. - Verified the test fails without the fix by observing the retained, already-disposed `CanvasDrawingSession`. - Core DeviceTests: 2,092 total, 1,981 passed, 111 skipped, 0 failed. - Ran the exact issue attachment twice for 120 seconds each with 3,848 presses and 38,480 pointer moves per run; both exited cleanly with code 0 and no correlated Windows application errors. - Also validated custom/default fonts, `ManipulationMode.All`/`None`, multiple views, redraw, resize, unload, and graceful shutdown. ### Video verification #### Before — original reported crash The issue author's original recording shows the attached app failing during pointer interaction: https://github.com/user-attachments/assets/eecd8e89-17c9-4764-b21e-9e6c15141fb4 #### After — fixed DLL under sustained pointer stress The exact attached application was rebuilt with an ABI-compatible fixed `Microsoft.Maui.Graphics.Win2D.WinUI.Desktop.dll`, then exercised with real `SendInput` pointer presses and moves for 120 seconds: https://github.com/user-attachments/assets/41a3e68c-e048-4d09-b677-aec1a9bc3af7 This recorded run delivered 11,622 presses and 116,220 pointer moves, then closed normally with exit code `0`. No correlated `Application Error` or `.NET Runtime` event was recorded. The native crash is intermittent: fresh recording attempts against the original DLL did not fail during the capture session, so the before clip above is the reporter's genuine original failure rather than a clean run being mislabeled or a crash being staged. The deterministic regression evidence is the baseline test retaining an already-disposed `CanvasDrawingSession`; the same test passes after this change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 01dac3d5-7cea-4af6-ba68-fdc87f9ceb54
<!-- 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! ### Description Fixes #29418. On Windows, `W2DGraphicsView` stored Win2D's callback-scoped `CanvasDrawingSession` on its persistent canvas. Win2D disposes that native session after the draw callback returns, but the stale managed reference remained available across repeated pointer-driven redraws and shutdown, leading to native access violations and heap corruption. This change clears the drawing session after canvas state has been reset. The nested cleanup guarantees the session and thread-local canvas owner are released even if state reset throws. @Kamalesh-Periyasamy, once the PR artifacts are available, could you please try them with your original application and let us know whether they resolve the crash? ### Tests - Added a Windows device test that performs an initial draw plus 100 explicit invalidation/draw cycles and verifies the drawing session is released after every callback. - Verified the test fails without the fix by observing the retained, already-disposed `CanvasDrawingSession`. - Core DeviceTests: 2,092 total, 1,981 passed, 111 skipped, 0 failed. - Ran the exact issue attachment twice for 120 seconds each with 3,848 presses and 38,480 pointer moves per run; both exited cleanly with code 0 and no correlated Windows application errors. - Also validated custom/default fonts, `ManipulationMode.All`/`None`, multiple views, redraw, resize, unload, and graceful shutdown. ### Video verification #### Before — original reported crash The issue author's original recording shows the attached app failing during pointer interaction: https://github.com/user-attachments/assets/eecd8e89-17c9-4764-b21e-9e6c15141fb4 #### After — fixed DLL under sustained pointer stress The exact attached application was rebuilt with an ABI-compatible fixed `Microsoft.Maui.Graphics.Win2D.WinUI.Desktop.dll`, then exercised with real `SendInput` pointer presses and moves for 120 seconds: https://github.com/user-attachments/assets/41a3e68c-e048-4d09-b677-aec1a9bc3af7 This recorded run delivered 11,622 presses and 116,220 pointer moves, then closed normally with exit code `0`. No correlated `Application Error` or `.NET Runtime` event was recorded. The native crash is intermittent: fresh recording attempts against the original DLL did not fail during the capture session, so the before clip above is the reporter's genuine original failure rather than a clean run being mislabeled or a crash being staged. The deterministic regression evidence is the baseline test retaining an already-disposed `CanvasDrawingSession`; the same test passes after this change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 01dac3d5-7cea-4af6-ba68-fdc87f9ceb54
<!-- 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! ### Description Fixes #29418. On Windows, `W2DGraphicsView` stored Win2D's callback-scoped `CanvasDrawingSession` on its persistent canvas. Win2D disposes that native session after the draw callback returns, but the stale managed reference remained available across repeated pointer-driven redraws and shutdown, leading to native access violations and heap corruption. This change clears the drawing session after canvas state has been reset. The nested cleanup guarantees the session and thread-local canvas owner are released even if state reset throws. @Kamalesh-Periyasamy, once the PR artifacts are available, could you please try them with your original application and let us know whether they resolve the crash? ### Tests - Added a Windows device test that performs an initial draw plus 100 explicit invalidation/draw cycles and verifies the drawing session is released after every callback. - Verified the test fails without the fix by observing the retained, already-disposed `CanvasDrawingSession`. - Core DeviceTests: 2,092 total, 1,981 passed, 111 skipped, 0 failed. - Ran the exact issue attachment twice for 120 seconds each with 3,848 presses and 38,480 pointer moves per run; both exited cleanly with code 0 and no correlated Windows application errors. - Also validated custom/default fonts, `ManipulationMode.All`/`None`, multiple views, redraw, resize, unload, and graceful shutdown. ### Video verification #### Before — original reported crash The issue author's original recording shows the attached app failing during pointer interaction: https://github.com/user-attachments/assets/eecd8e89-17c9-4764-b21e-9e6c15141fb4 #### After — fixed DLL under sustained pointer stress The exact attached application was rebuilt with an ABI-compatible fixed `Microsoft.Maui.Graphics.Win2D.WinUI.Desktop.dll`, then exercised with real `SendInput` pointer presses and moves for 120 seconds: https://github.com/user-attachments/assets/41a3e68c-e048-4d09-b677-aec1a9bc3af7 This recorded run delivered 11,622 presses and 116,220 pointer moves, then closed normally with exit code `0`. No correlated `Application Error` or `.NET Runtime` event was recorded. The native crash is intermittent: fresh recording attempts against the original DLL did not fail during the capture session, so the before clip above is the reporter's genuine original failure rather than a clean run being mislabeled or a crash being staged. The deterministic regression evidence is the baseline test retaining an already-disposed `CanvasDrawingSession`; the same test passes after this change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 01dac3d5-7cea-4af6-ba68-fdc87f9ceb54
<!-- 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! ### Description Fixes #29418. On Windows, `W2DGraphicsView` stored Win2D's callback-scoped `CanvasDrawingSession` on its persistent canvas. Win2D disposes that native session after the draw callback returns, but the stale managed reference remained available across repeated pointer-driven redraws and shutdown, leading to native access violations and heap corruption. This change clears the drawing session after canvas state has been reset. The nested cleanup guarantees the session and thread-local canvas owner are released even if state reset throws. @Kamalesh-Periyasamy, once the PR artifacts are available, could you please try them with your original application and let us know whether they resolve the crash? ### Tests - Added a Windows device test that performs an initial draw plus 100 explicit invalidation/draw cycles and verifies the drawing session is released after every callback. - Verified the test fails without the fix by observing the retained, already-disposed `CanvasDrawingSession`. - Core DeviceTests: 2,092 total, 1,981 passed, 111 skipped, 0 failed. - Ran the exact issue attachment twice for 120 seconds each with 3,848 presses and 38,480 pointer moves per run; both exited cleanly with code 0 and no correlated Windows application errors. - Also validated custom/default fonts, `ManipulationMode.All`/`None`, multiple views, redraw, resize, unload, and graceful shutdown. ### Video verification #### Before — original reported crash The issue author's original recording shows the attached app failing during pointer interaction: https://github.com/user-attachments/assets/eecd8e89-17c9-4764-b21e-9e6c15141fb4 #### After — fixed DLL under sustained pointer stress The exact attached application was rebuilt with an ABI-compatible fixed `Microsoft.Maui.Graphics.Win2D.WinUI.Desktop.dll`, then exercised with real `SendInput` pointer presses and moves for 120 seconds: https://github.com/user-attachments/assets/41a3e68c-e048-4d09-b677-aec1a9bc3af7 This recorded run delivered 11,622 presses and 116,220 pointer moves, then closed normally with exit code `0`. No correlated `Application Error` or `.NET Runtime` event was recorded. The native crash is intermittent: fresh recording attempts against the original DLL did not fail during the capture session, so the before clip above is the reporter's genuine original failure rather than a clean run being mislabeled or a crash being staged. The deterministic regression evidence is the baseline test retaining an already-disposed `CanvasDrawingSession`; the same test passes after this change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 01dac3d5-7cea-4af6-ba68-fdc87f9ceb54
<!-- 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! ### Description Fixes #29418. On Windows, `W2DGraphicsView` stored Win2D's callback-scoped `CanvasDrawingSession` on its persistent canvas. Win2D disposes that native session after the draw callback returns, but the stale managed reference remained available across repeated pointer-driven redraws and shutdown, leading to native access violations and heap corruption. This change clears the drawing session after canvas state has been reset. The nested cleanup guarantees the session and thread-local canvas owner are released even if state reset throws. @Kamalesh-Periyasamy, once the PR artifacts are available, could you please try them with your original application and let us know whether they resolve the crash? ### Tests - Added a Windows device test that performs an initial draw plus 100 explicit invalidation/draw cycles and verifies the drawing session is released after every callback. - Verified the test fails without the fix by observing the retained, already-disposed `CanvasDrawingSession`. - Core DeviceTests: 2,092 total, 1,981 passed, 111 skipped, 0 failed. - Ran the exact issue attachment twice for 120 seconds each with 3,848 presses and 38,480 pointer moves per run; both exited cleanly with code 0 and no correlated Windows application errors. - Also validated custom/default fonts, `ManipulationMode.All`/`None`, multiple views, redraw, resize, unload, and graceful shutdown. ### Video verification #### Before — original reported crash The issue author's original recording shows the attached app failing during pointer interaction: https://github.com/user-attachments/assets/eecd8e89-17c9-4764-b21e-9e6c15141fb4 #### After — fixed DLL under sustained pointer stress The exact attached application was rebuilt with an ABI-compatible fixed `Microsoft.Maui.Graphics.Win2D.WinUI.Desktop.dll`, then exercised with real `SendInput` pointer presses and moves for 120 seconds: https://github.com/user-attachments/assets/41a3e68c-e048-4d09-b677-aec1a9bc3af7 This recorded run delivered 11,622 presses and 116,220 pointer moves, then closed normally with exit code `0`. No correlated `Application Error` or `.NET Runtime` event was recorded. The native crash is intermittent: fresh recording attempts against the original DLL did not fail during the capture session, so the before clip above is the reporter's genuine original failure rather than a clean run being mislabeled or a crash being staged. The deterministic regression evidence is the baseline test retaining an already-disposed `CanvasDrawingSession`; the same test passes after this change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 01dac3d5-7cea-4af6-ba68-fdc87f9ceb54
<!-- 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! ### Description Fixes #29418. On Windows, `W2DGraphicsView` stored Win2D's callback-scoped `CanvasDrawingSession` on its persistent canvas. Win2D disposes that native session after the draw callback returns, but the stale managed reference remained available across repeated pointer-driven redraws and shutdown, leading to native access violations and heap corruption. This change clears the drawing session after canvas state has been reset. The nested cleanup guarantees the session and thread-local canvas owner are released even if state reset throws. @Kamalesh-Periyasamy, once the PR artifacts are available, could you please try them with your original application and let us know whether they resolve the crash? ### Tests - Added a Windows device test that performs an initial draw plus 100 explicit invalidation/draw cycles and verifies the drawing session is released after every callback. - Verified the test fails without the fix by observing the retained, already-disposed `CanvasDrawingSession`. - Core DeviceTests: 2,092 total, 1,981 passed, 111 skipped, 0 failed. - Ran the exact issue attachment twice for 120 seconds each with 3,848 presses and 38,480 pointer moves per run; both exited cleanly with code 0 and no correlated Windows application errors. - Also validated custom/default fonts, `ManipulationMode.All`/`None`, multiple views, redraw, resize, unload, and graceful shutdown. ### Video verification #### Before — original reported crash The issue author's original recording shows the attached app failing during pointer interaction: https://github.com/user-attachments/assets/eecd8e89-17c9-4764-b21e-9e6c15141fb4 #### After — fixed DLL under sustained pointer stress The exact attached application was rebuilt with an ABI-compatible fixed `Microsoft.Maui.Graphics.Win2D.WinUI.Desktop.dll`, then exercised with real `SendInput` pointer presses and moves for 120 seconds: https://github.com/user-attachments/assets/41a3e68c-e048-4d09-b677-aec1a9bc3af7 This recorded run delivered 11,622 presses and 116,220 pointer moves, then closed normally with exit code `0`. No correlated `Application Error` or `.NET Runtime` event was recorded. The native crash is intermittent: fresh recording attempts against the original DLL did not fail during the capture session, so the before clip above is the reporter's genuine original failure rather than a clean run being mislabeled or a crash being staged. The deterministic regression evidence is the baseline test retaining an already-disposed `CanvasDrawingSession`; the same test passes after this change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 01dac3d5-7cea-4af6-ba68-fdc87f9ceb54
<!-- 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! ### Description Fixes #29418. On Windows, `W2DGraphicsView` stored Win2D's callback-scoped `CanvasDrawingSession` on its persistent canvas. Win2D disposes that native session after the draw callback returns, but the stale managed reference remained available across repeated pointer-driven redraws and shutdown, leading to native access violations and heap corruption. This change clears the drawing session after canvas state has been reset. The nested cleanup guarantees the session and thread-local canvas owner are released even if state reset throws. @Kamalesh-Periyasamy, once the PR artifacts are available, could you please try them with your original application and let us know whether they resolve the crash? ### Tests - Added a Windows device test that performs an initial draw plus 100 explicit invalidation/draw cycles and verifies the drawing session is released after every callback. - Verified the test fails without the fix by observing the retained, already-disposed `CanvasDrawingSession`. - Core DeviceTests: 2,092 total, 1,981 passed, 111 skipped, 0 failed. - Ran the exact issue attachment twice for 120 seconds each with 3,848 presses and 38,480 pointer moves per run; both exited cleanly with code 0 and no correlated Windows application errors. - Also validated custom/default fonts, `ManipulationMode.All`/`None`, multiple views, redraw, resize, unload, and graceful shutdown. ### Video verification #### Before — original reported crash The issue author's original recording shows the attached app failing during pointer interaction: https://github.com/user-attachments/assets/eecd8e89-17c9-4764-b21e-9e6c15141fb4 #### After — fixed DLL under sustained pointer stress The exact attached application was rebuilt with an ABI-compatible fixed `Microsoft.Maui.Graphics.Win2D.WinUI.Desktop.dll`, then exercised with real `SendInput` pointer presses and moves for 120 seconds: https://github.com/user-attachments/assets/41a3e68c-e048-4d09-b677-aec1a9bc3af7 This recorded run delivered 11,622 presses and 116,220 pointer moves, then closed normally with exit code `0`. No correlated `Application Error` or `.NET Runtime` event was recorded. The native crash is intermittent: fresh recording attempts against the original DLL did not fail during the capture session, so the before clip above is the reporter's genuine original failure rather than a clean run being mislabeled or a crash being staged. The deterministic regression evidence is the baseline test retaining an already-disposed `CanvasDrawingSession`; the same test passes after this change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 01dac3d5-7cea-4af6-ba68-fdc87f9ceb54
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
Fixes #29418.
On Windows,
W2DGraphicsViewstored Win2D's callback-scopedCanvasDrawingSessionon its persistent canvas. Win2D disposes that native session after the draw callback returns, but the stale managed reference remained available across repeated pointer-driven redraws and shutdown, leading to native access violations and heap corruption.This change clears the drawing session after canvas state has been reset. The nested cleanup guarantees the session and thread-local canvas owner are released even if state reset throws.
@Kamalesh-Periyasamy, once the PR artifacts are available, could you please try them with your original application and let us know whether they resolve the crash?
Tests
CanvasDrawingSession.ManipulationMode.All/None, multiple views, redraw, resize, unload, and graceful shutdown.Video verification
Before — original reported crash
The issue author's original recording shows the attached app failing during pointer interaction:
MauiApp1_CdeG31uL7s.mp4
After — fixed DLL under sustained pointer stress
The exact attached application was rebuilt with an ABI-compatible fixed
Microsoft.Maui.Graphics.Win2D.WinUI.Desktop.dll, then exercised with realSendInputpointer presses and moves for 120 seconds:issue-29418-fixed-pointer-stress.mp4
This recorded run delivered 11,622 presses and 116,220 pointer moves, then closed normally with exit code
0. No correlatedApplication Erroror.NET Runtimeevent was recorded.The native crash is intermittent: fresh recording attempts against the original DLL did not fail during the capture session, so the before clip above is the reporter's genuine original failure rather than a clean run being mislabeled or a crash being staged. The deterministic regression evidence is the baseline test retaining an already-disposed
CanvasDrawingSession; the same test passes after this change.