Random ran = new Random();
byte tmp = (byte)ran.Next(10);
Is there an alternative to this code? It does not seem to have fully random behavior.
There are multiple reasons for why this could occur. One common problem is to create multiple instances of the Random
class within a program. When using the Random
class you should only create one instance and generate numbers from that. The article Create better random numbers in C# has a good explanation of why and explains why not doing this could lead to a problem.
Another common scenario is accessing the Random
class object from multiple threads. System.Random
is not thread safe (see the Remarks section of the documentation for Random
) and thus can lead to unexpected and unwanted behavior. If using it in a multi-threaded environment then you need to be sure to use some form of locking to prevent multiple threads trying to generate random numbers at the same time.
For higher degrees of security and randomness you can use a cryptographically secure random number generator like
System.Security.Cryptography.RNGCryptoServiceProvider. Note that using a more secure random number generator will incur a performance penalty in comparison with System.Random
.
If you don't need something cryptographically secure, but still want something that is more "random" than the Random
class you can explore using other PRNG's such as Mersenne Twister. There are lots of options, each with different characteristics and performance profiles. Which you choose is heavily dependent on your goal.
It might be simpler than that. If you can this method in a tight loop:
for (int i = 0; i < 1000; i++)
{
Random ran = new Random();
byte tmp;
tmp = (byte)ran.Next(10);
}
You might see the same number over and over. Make sure you create the Random object outside any sort of looping.
Random ran = new Random();
for (int i = 0; i < 1000; i++)
{
byte tmp;
tmp = (byte)ran.Next(10);
}
That said, it is true that the crypto provider is better. But you're only getting randoms between 0 & 9 so how random does it have to be?
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