Skip to content

Fix Random.Shared giving identical sequences on threads started together - #638

Merged
SimonCropp merged 1 commit into
mainfrom
fix/random-shared-seed
Oct 11, 2026
Merged

SimonCropp merged 1 commit into
mainfrom
fix/random-shared-seed

Conversation

@SimonCropp

Copy link
Copy Markdown
Owner

Bug

The Random.Shared polyfill (below net6) keeps a [ThreadStatic] Random per thread, and created each one with new Random(). On .NET Framework the parameterless constructor seeds from Environment.TickCount, so threads that first touch Random.Shared within the same tick get identically seeded instances, and so identical sequences. Sixteen threads released together by a Barrier all produced the same four numbers.

Fix

Each thread's instance is now seeded from a single process-wide Random, read under a lock. Every thread gets a different seed regardless of when it starts.

Test

SharedDiffersAcrossThreadsStartedTogether starts 16 dedicated threads, releases them together with a Barrier, takes four values from Random.Shared on each, and asserts all 16 sequences differ. Before the fix it found 1 distinct sequence on net48. It passes on net48 (polyfill) and net10.0 (BCL).

@SimonCropp SimonCropp added this to the 11.4.4 milestone Oct 11, 2026
@SimonCropp
SimonCropp merged commit 3c53cf3 into main Oct 11, 2026
5 checks passed
@SimonCropp
SimonCropp deleted the fix/random-shared-seed branch October 11, 2026 22:12
This was referenced Oct 12, 2026
This was referenced Oct 14, 2026
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.

1 participant