Skip to content

Avoid JSRuntime cancellation race with EndInvokeJS#66834

Open
alirezafzali wants to merge 5 commits into
dotnet:mainfrom
alirezafzali:fix-jsruntime-cancellation-race
Open

Avoid JSRuntime cancellation race with EndInvokeJS#66834
alirezafzali wants to merge 5 commits into
dotnet:mainfrom
alirezafzali:fix-jsruntime-cancellation-race

Conversation

@alirezafzali

Copy link
Copy Markdown

Avoid JSRuntime cancellation race with EndInvokeJS

Summary of the changes

Avoid race between JSRuntime cancellation and EndInvokeJS

Description

This change fixes a race condition in Microsoft.JSInterop.JSRuntime where both the cancellation callback and EndInvokeJS could concurrently attempt to complete the same TaskCompletionSource.

The issue was reported in dotnet/maui because the visible crash occurs in BlazorWebView, but the underlying race condition exists in Microsoft.JSInterop.JSRuntime within aspnetcore.

Previously, the cancellation callback captured the local TaskCompletionSource directly and called TrySetCanceled, while EndInvokeJS could simultaneously remove the same task from _pendingTasks and attempt to complete it via SetResult or SetException. In some cases this resulted in double-completion and an unhandled exception.

This change updates the cancellation path to first atomically remove the task from _pendingTasks using TryRemove. Only the code path that successfully removes the task is allowed to complete it.

Additionally, the EndInvokeJS exception handling path was hardened to use non-throwing completion semantics.

Regression tests were added to verify:

  • cancellation followed by EndInvokeJS
  • successful EndInvokeJS followed by cancellation
  • failed EndInvokeJS followed by cancellation

Fixes dotnet/maui#31943

@alirezafzali alirezafzali requested a review from a team as a code owner May 25, 2026 22:33
@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components label May 25, 2026
@alirezafzali

Copy link
Copy Markdown
Author

@dotnet-policy-service agree

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Race condition in JSRuntime on cancellation

1 participant