how to make a c# thread-safe random number generator

前端 未结 4 689
粉色の甜心
粉色の甜心 2021-01-14 04:27

I have a loop in my code

Parallel.For(0, Cnts.MosqPopulation, i => { DoWork() });

however in the DoWork() function, there a

4条回答
  •  旧巷少年郎
    2021-01-14 04:51

    Using the ThreadStatic attribute and a custom getter, you will get a single Random instance per thread. If this is not acceptable, use locks.

    public static class Utils
    {
        [ThreadStatic]
        private static Random __random;
    
        public static Random Random => __random??(__random=new Random());
    }
    

    The ThreadStatic attribute does not run the initializer on each thread so you are responsible for doing so in your accessor. Also think about your seed initializer, you can use something like

    new Random((int) ((1+Thread.CurrentThread.ManagedThreadId) * DateTime.UtcNow.Ticks) )
    

提交回复
热议问题