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:
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.
For more information, see the Random (Int32) constructor. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator, so the previously described limitation does not apply. Different Random objects created in close succession produce different sets of random numbers in .NET Core.
If the same seed is used for separate Random objects, they will generate the same series of random numbers. This can be useful for creating a test suite that processes random values, or for replaying games that derive their data from random numbers.
Note that the Random class in .NET Core does not have this limitation. On the .NET Framework, initializing two random number generators in a tight loop or in rapid succession creates two random number generators that can produce identical sequences of random numbers.
The implementation of the random number generator in the Random class isn't guaranteed to remain the same across major versions of the .NET Framework. As a result, you shouldn't assume that the same seed will result in the same pseudo-random sequence in different versions of the .NET Framework.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With