8

I've seen several articles talking about not generating too many System.Random instances too closely together because they'll be seeded with the same value from the system clock and thus return the same set of numbers:

  1. https://stackoverflow.com/a/2706537/2891835
  2. https://codeblog.jonskeet.uk/2009/11/04/revisiting-randomness/
  3. https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.8#instantiating-the-random-number-generator

That appears to be true for .net framework 4.8. Looking at the source code for .net core, however, it looks like instances of System.Random generated on the same thread are seeded from a [ThreadStatic] generator. So it would seem to me that, in .net core, you are now safe to do something like:

Random[] randoms = new Random[1000];
for (int i = 0; i < randoms.Length; i++)
{
  randoms[i] = new Random();
}
// use Random instances and they'll all have distinct generated patterns

Is this true? Am I missing something?

Note: Assume we're talking about a single thread here (although I'm not sure it matters because it looks like .net core uses bcrypt or something to seed the global generator per-thread?).

EDIT: This is now tracked in this ticket.

Mark Lodato
  • 386
  • 3
  • 14
  • 3
    I'm not sure why you would ever need an *array* of `Random`. What's the use-case for this? –  Aug 23 '19 at 18:17
  • 1
    @Igor Sorry, maybe miscommunication - the question wasn't meant to be about best practices for `System.Random`. I'm wondering if, in .net core, `System.Random` instances are seeded differently than `System.Random` instances in .net framework or if I'm reading out of date documentation or reading documentation incorrectly or something. – Mark Lodato Aug 23 '19 at 18:19

1 Answers1

5

Is this true? Am I missing something?

I believe your reading of the source code is correct. But you shouldn't rely on this behavior unless it's documented. My guess is that the documentation simply hasn't kept up with the implementation, but you can open an issue here to get the docs updated.

.NET Core has lots of little enhancements like this that you might hesitate to make to .NET Framework for backwards-compatibility reasons.

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67