I need to quickly generate random floating-point numbers across multiple running threads. I\'ve tried using System.Random
, but it\'s too slow for my needs and it re
Here is my take on it (requires .net 4.0):
public static class RandomGenerator
{
private static object locker = new object();
private static Random seedGenerator = new Random(Environment.TickCount);
public static double GetRandomNumber()
{
int seed;
lock (locker)
{
seed = seedGenerator.Next(int.MinValue, int.MaxValue);
}
var random = new Random(seed);
return random.NextDouble();
}
}
and a test to check that for 1000 iterations each value is unique:
[TestFixture]
public class RandomGeneratorTests
{
[Test]
public void GetRandomNumber()
{
var collection = new BlockingCollection();
Parallel.ForEach(Enumerable.Range(0, 1000), i =>
{
var random = RandomGenerator.GetRandomNumber();
collection.Add(random);
});
CollectionAssert.AllItemsAreUnique(collection);
}
}
I don't guarantee that it will never return a duplicate value, but I've run the test with 10000 iterations and it passed the test.