连续相同随机数解决办法

如果在短时间内生成随机数的话会出现连续相同的数

为了解决这个问题,引入随机数种子

 1   class Program
 2     {
 3         static bool flag = true;
 4         static void Main(string[] args)
 5         {
 6             ChangeFlag();
 7 
 8             while (flag)
 9             {
10                 //Random random = new Random();
11                 Random random = new Random(GetRandomSeed());
12                 Console.WriteLine(random.Next(0, 100));
13             }
14             Console.ReadLine();
15         }
16 
17         private static Task<bool> GetFlag()
18         {
19             return Task.Run(() =>
20             {
21                 return !flag;
22             });
23         }
24         private async static void ChangeFlag()
25         {
26             await Task.Delay(2000);
27             flag = await GetFlag();
28         }
29 
30         public static int GetRandomSeed()
31         {
32             System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
33             byte[] bytes = new byte[4];
34             rng.GetBytes(bytes);
35             return BitConverter.ToInt32(bytes, 0);
36         }
37     }
View Code

为什么会出现这种情况不知道原因,如果有知道原因的道友还望不吝指教。

注:如果将random的赋值放在循环之外的话,其实也可以得到不连续的随机数,也能解决这个问题。

原文地址:https://www.cnblogs.com/XzcBlog/p/4037087.html