Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jul 23, 2025

A common pattern we use in other places: https://github.com/search?q=repo%3Amicrosoft%2Fplaywright-dotnet+%2Fforeach.*s%5C.ToArray%5C%28%5C%29%5C%29%2F&type=code

Fixes a thread safety issue in Selectors.cs that causes System.InvalidOperationException: Collection was modified; enumeration operation may not execute when running tests in parallel.

Problem

The issue occurs in two methods in the Selectors class:

  • SetTestIdAttribute() at line 70
  • RegisterAsync() at line 56

Both methods enumerate over the _contextsForSelectors list while other threads may be modifying it (adding/removing browser contexts), causing the classic collection modification exception.

// This throws InvalidOperationException under parallel execution
foreach (var context in _contextsForSelectors)
{
    context.SendMessageToServerAsync("setTestIdAttributeName", ...);
}

The _contextsForSelectors list is modified by:

  • Browser.ConnectToBrowserType() and Browser.DidCreateContext() - adds contexts
  • BrowserContext.OnClose() - removes contexts

Solution

Create a snapshot of the list before enumeration using ToArray() to prevent the collection modification exception:

// Thread-safe enumeration using snapshot
foreach (var context in _contextsForSelectors.ToArray())
{
    context.SendMessageToServerAsync("setTestIdAttributeName", ...);
}

This approach:

  • ✅ Fixes the race condition without breaking existing functionality
  • ✅ Has minimal performance impact (only creates snapshot when contexts exist)
  • ✅ Maintains thread safety for parallel test execution
  • ✅ No changes to public API

Fixes #3207.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot AI changed the title [WIP] [Bug]: System.InvalidOperationException : Collection was modified; enumeration operation may not execute. Fix InvalidOperationException in Selectors when running parallel tests Jul 23, 2025
Copilot AI requested a review from mxschmitt July 23, 2025 10:51
@mxschmitt mxschmitt marked this pull request as ready for review July 23, 2025 11:13
@mxschmitt mxschmitt merged commit 888c053 into main Jul 30, 2025
16 checks passed
@mxschmitt mxschmitt deleted the copilot/fix-3207 branch July 30, 2025 12:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: System.InvalidOperationException : Collection was modified; enumeration operation may not execute.

4 participants