可能的重复:
随机数生成器没有按我计划的方式工作(C#) https://stackoverflow.com/questions/767999/random-number-generator-not-working-the-way-i-had-planned-c
我创建了一个返回随机数的方法:
public static int SelectRandomMachine(int max)
{
int seed = (int)DateTime.Now.Ticks;
Random rndNumber = new Random(seed);
int randMachine = rndNumber.Next(0, max);
return randMachine;
}
如果我调用该方法两次,目前它会返回相同的随机数:
randM1 = SelectRandomMachine(maxNumber);
randM2 = SelectRandomMachine(maxNumber);
任何建议将不胜感激。
提示看这一行:
int seed = (int)DateTime.Now.Ticks;
如果您快速连续执行该行两次,您认为值会是多少?
例如:
int seed1 = (int)DateTime.Now.Ticks;
int seed2 = (int)DateTime.Now.Ticks;
// Write it out *after* executing; console output can take a while
Console.WriteLine(seed1);
Console.WriteLine(seed2);
See my 关于随机性的文章 http://csharpindepth.com/Articles/Chapter12/Random.aspx获取解决方案和更多信息。
编辑:这是一个缺乏线程安全导致问题的快速而肮脏的例子:
using System.Collections.Generic;
using System.Threading;
class Program
{
const int Iterations = 1000000;
static readonly Random rng = new Random();
static void Main(string[] args)
{
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 8; i++)
{
Thread t = new Thread(ExerciseRandom);
threads.Add(t);
t.Start();
}
foreach (Thread t in threads)
{
t.Join();
}
Console.WriteLine(rng.Next());
Console.WriteLine(rng.Next());
Console.WriteLine(rng.Next());
}
static void ExerciseRandom()
{
for (int i = 0; i < Iterations; i++)
{
rng.Next();
}
}
}
我的盒子上的输出:
0
0
0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)