When C # is used to generate random numbers, we generally do not want to duplicate them, but sometimes it is difficult to avoid this situation.
For exampleProgramWhen multiple random numbers are generated consecutively and the interval between them is very short, a problem occurs. The most basic way to generate a random number is:
However, this will not solve the problem mentioned above, and will generate many identical random numbers. Therefore, you must add a random number factor parameter at the time of generation to avoid repeated possibilities, but how should we determine this random number factor?
I have tried to use the time in milliseconds before, and I think it is okay:
1
|
RandomR= New Random(Unchecked((Int)(Datetime.Now.Ticks))); |
This is also the practice on msdn, but even so, the computer is still running too fast, so there will be a chance to repeat, and there are still a lot of opportunities, then I try to add tick to 1 before each operation, but it still cannot be completely solved, but the probability is reduced.
However, there will always be a solution. In fact, there is a way to ensure that there are no duplicates, that is, using guid as a random factor. As we all know, GUID is absolutely impossible to be repeated, therefore, using it as a factor is the best choice,CodeAs follows:
1
|
RandomR= New Random(Guid.Newguid().Gethashcode()); |
Oh, this will solve the above repeated problems!