Test today, in a loop to assign a random value to the entity attribute, and then generate an entity collection, suddenly found that the generated entity collection of all entities corresponding property values are the same, debugging but found that the value is not repeated, the degree Niang later found the problem-- The random class is a class that generates pseudo-random numbers, with two constructors, one for direct new random () and the other for new Random (INT32), which generates a random number based on the system time that triggered the tick. The latter can set the seed of the trigger itself, the system defaults to uncheck ((INT) DateTime.Now.Ticks) as the parameter seed, so if the computer is running fast (like a small loop, the execution speed is too fast), if the trigger Randm function interval is very short, It is possible to generate the same random number, because pseudo-random numbers, in the internal generation mechanism of random is still a certain regularity, not the true meaning of completely random.
There are generally 2 ways of solving the problem:
1, the method of delay.
Use Thread.Sleep (100);//The number of milliseconds in parentheses
2, increase the random number of non-repetition probability of the seed generation method, in the New random (Seedparam) to ensure that Seedparam is unique
DEMO:
1. Non-processing random (repeated phenomenon)
for(inti =0; I <5; i++) {Random R=NewRandom (); intnum = R.next (10000,99999);//randomly generates a 5-bit integer stringTempStr =string. Empty; for(intj =0; J <4; J + +) {R=NewRandom (); intx = R.next ( $, -);//65-90 represents a-Z ASCII value CharA = (Char) x; TempStr+=a.tostring (); } Console.WriteLine ("Num"+ i.tostring () +"The values are:"+num); Console.WriteLine ("TempStr"+ i.tostring () +"The values are:"+tempstr); }
The results of the implementation are as follows:
2. Random generation with increased random seed (no repetition)
for(inti =0; I <5; i++) {Random R=NewRandom (int. Parse (DateTime.Now.ToString ("hhmmssfff")) +i); intnum = R.next (10000,99999);//randomly generates a 5-bit integer stringTempStr =string. Empty; for(intj =0; J <4; J + +) {R=NewRandom (int. Parse (DateTime.Now.ToString ("hhmmssfff")) + i +j); intx = R.next ( $, -);//65-90 represents a-Z ASCII value CharA = (Char) x; TempStr+=a.tostring (); } Console.WriteLine ("Num"+ i.tostring () +"The values are:"+num); Console.WriteLine ("TempStr"+ i.tostring () +"The values are:"+tempstr); }
The results of the implementation are as follows:
C # Generate random number repetition problem