用于C#的快速线程安全随机数发生器

Mar*_*inS 0 c# random parallel-processing performance generator

我需要在多个正在运行的线程中快速生成随机浮点数.我尝试过使用System.Random,但它对我的需求来说太慢了,它在多个线程中返回相同的数字.(当我在一个线程中运行我的应用程序时,它工作正常.)另外,我需要确保生成的数字在0到100之间.

这是我现在正在尝试的内容:

number = random.NextDouble() * 100;
Run Code Online (Sandbox Code Playgroud)

我该怎么办呢?

Tre*_*ley 5

这是我对它的看法(需要.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();
    }
}
Run Code Online (Sandbox Code Playgroud)

并且测试检查1000次迭代每个值是唯一的:

[TestFixture]
public class RandomGeneratorTests
{
    [Test]
    public void GetRandomNumber()
    {
        var collection = new BlockingCollection<double>();

        Parallel.ForEach(Enumerable.Range(0, 1000), i =>
        {
            var random = RandomGenerator.GetRandomNumber();
            collection.Add(random);
        });

        CollectionAssert.AllItemsAreUnique(collection);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不保证它永远不会返回重复值,但我已经运行了10000次迭代的测试并且它通过了测试.

  • 这不是线程安全的,因为它在所有线程中共享一个`Random`实例 - "seedGenerator".迟早这将在多线程环境中破裂. (4认同)