Fast thread-safe random number generator for C#

前端 未结 3 1804
自闭症患者
自闭症患者 2021-01-26 06:57

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-26 07:33

    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.

提交回复
热议问题