Repository navigation
Fix Random.Shared giving identical sequences on threads started together - #638
Merged
Merged
Conversation
This was referenced Oct 12, 2026
This was referenced Oct 14, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Bug
The
Random.Sharedpolyfill (below net6) keeps a[ThreadStatic]Randomper thread, and created each one withnew Random(). On .NET Framework the parameterless constructor seeds fromEnvironment.TickCount, so threads that first touchRandom.Sharedwithin the same tick get identically seeded instances, and so identical sequences. Sixteen threads released together by aBarrierall 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
SharedDiffersAcrossThreadsStartedTogetherstarts 16 dedicated threads, releases them together with aBarrier, takes four values fromRandom.Sharedon 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).