Real random c# generator

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.

Tags:

C# 4.0