For a long time, system. Random has been used well, and every random number is almost satisfactory. As follows: Code System. Random R = New Random ();
Int S = R. Next ();
However, when I am working on a project and suddenly encounter a large number of random numbers, sometimes the random numbers are not random, and the random numbers before and after are often the same. What is going on?
Google has been using the following code for a long time
System. Random R = New Random (uncheck (( Int ) Datetime. Now. ticks ));
Int S = R. Next ();
The effect is the same. After reading msdn, we found that random () uses time as the seed of the random generator by default. ticks hasn't changed yet when a large number of random numbers are used. As we all know, currently, all of our commonly used random generators are pseudo-random numbers and require seeds. When the seeds are the same, the random sequences are the same, so the random numbers are not random.
After finding the problem, we took the right remedy and paused for a millisecond each time before getting the random number.
System. Threading. thread. Sleep ( 1 );
In this way, each random seed is different, so that the random number is more random.
Complete code:
System. Random random = New Random ();
System. Threading. thread. Sleep ( 1 );
IntSerial=Random. Next ();