Skip to content

Synchronize Process.Exited subscription updates - #136887

Merged
adamsitnik merged 2 commits into
dotnet:mainfrom
MattKotsenas:bugfix/process-exited-event-race
Nov 17, 2026
Merged

adamsitnik merged 2 commits into
dotnet:mainfrom
MattKotsenas:bugfix/process-exited-event-race

Conversation

@MattKotsenas

@MattKotsenas MattKotsenas commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

This PR synchronizes Exited subscription updates to prevent lost handlers during overlapping exit waits.

Exited updates a delegate field without synchronization, so overlapping additions and removals can overwrite one another. Replace that field with an event so the compiler generates thread-safe add/remove accessors, as it already does for OutputDataReceived and ErrorDataReceived. Public signatures and the OnExited/SynchronizingObject dispatch path are unchanged.

Motivating case and scope

I encountered this in an Aspire process runner that owns one Process, captures its streams, and waits for exit. Cancellation can send several independent operations into cleanup, where each waits for the process to terminate. Reduced to the relevant control flow, with the process already started and its output redirected:

var stdout = process.StandardOutput.ReadToEndAsync(token);
var stderr = process.StandardError.ReadToEndAsync(token);

await Task.WhenAll(
    GuardAsync(stdout),
    GuardAsync(stderr),
    GuardAsync(process.WaitForExitAsync(token)));

async Task GuardAsync(Task operation)
{
    try
    {
        await operation.ConfigureAwait(false);
    }
    catch
    {
        if (!process.HasExited)
        {
            process.Kill(entireProcessTree: true);
        }

        await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false);
        throw;
    }
}

The cleanup continuations can overlap, producing independent WaitForExitAsync calls on the same Process. I observed a cleanup wait remain pending after the process had exited and raised Exited, with that wait's event handler missing from the subscription list.

Making subscription updates atomic prevents these independent cleanup waits from losing handlers. This change does not make Process instances generally thread-safe.

Validation

The regression tests check callback counts after concurrent additions and removals, and require independent async waits to complete after process exit. They encourage contention but cannot guarantee the failing interleaving.

Each case ran 100 times against the unfixed and fixed libraries on Windows and Linux under WSL2. Each platform comparison used the same test assembly, without retries.

Observed failures out of 100 runs:

Case Windows unfixed Windows fixed WSL2 unfixed WSL2 fixed
Concurrent additions 98/100 0/100 99/100 0/100
Concurrent removals 99/100 0/100 100/100 0/100
Four independent async waits 45/100 0/100 13/100 0/100
Single async wait control 0/100 0/100 0/100 0/100

Subscription failures hit the final callback-count assertions. Async-wait failures hit the existing 30-second post-exit completion timeout.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 3, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-diagnostics-process
See info in area-owners.md if you want to be subscribed.

@MattKotsenas MattKotsenas changed the title Fix lost Process.Exited subscriptions Synchronize Process.Exited subscription updates Nov 3, 2026
Concurrent Exited additions and removals can overwrite delegate updates,
leaving WaitForExitAsync tasks pending after their process exits.

Use a field-like backing event for thread-safe subscription updates. Add
regression coverage for concurrent additions, removals, and async waits.
@MattKotsenas
MattKotsenas force-pushed the bugfix/process-exited-event-race branch from 518d51d to 1c89cd9 Compare November 3, 2026 13:51
@MattKotsenas

Copy link
Copy Markdown
Member Author

/cc @SamMonoRT as area owner for triage and review. If there's someone else to consult, please let me know. Thanks!

@jkotas
jkotas requested review from adamsitnik and a balanced review from Copilot November 12, 2026 04:11

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.

🟢 Approval recommended

No active review issues were identified for the change to make Process.Exited subscription updates atomic.

No open issues 🎉

What changed in this PR

This PR makes Process.Exited subscription updates atomic to prevent lost handlers during overlapping exit waits. It preserves the public API and existing event dispatch behavior without promising general Process thread safety.

Changes:

  • Replaces the private delegate field with an event that provides compiler-generated thread-safe add/remove accessors.
  • Adds callback-count tests for concurrent subscription additions and removals.
  • Adds exit-wait tests covering one waiter and four concurrent waiters.
File Description
src/​libraries/​System.Diagnostics.Process/​tests/​ProcessWaitingTests.cs Checks that independent async waits complete after process exit.
src/​libraries/​System.Diagnostics.Process/​tests/​ProcessTests.cs Checks callback counts after concurrent handler additions and removals.
src/​libraries/​System.Diagnostics.Process/​src/​System/​Diagnostics/​Process.cs Converts _onExited to a private event for atomic subscription updates.

Review effort: Balanced

@adamsitnik adamsitnik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@MattKotsenas thank you for your contribution! the fix LGTM, but PTAL at my comment and check if we can simplify the code even further. Thanks!

@adamsitnik adamsitnik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, thank you @MattKotsenas !

@adamsitnik

Copy link
Copy Markdown
Member

/ba-g the networking failure is unrelated

@adamsitnik
adamsitnik merged commit bb63b39 into dotnet:main Nov 17, 2026
66 of 68 checks passed
@adamsitnik

Copy link
Copy Markdown
Member

I encountered this in an Aspire process runner that owns one Proces

@MattKotsenas do you need to get this backported to .NET 10 or 11?

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

Labels

area-System.Diagnostics.Process community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants