Wednesday, January 30, 2013

C# Threadsafe Random


    ///     A threadsafe wrapper around .
    public static class Randem {

        private static int seed;

        static Randem() { seed = Environment.TickCount; }

        ///





        ///     Provide to each thread its own .
        ///
        private static readonly ThreadLocal< Random > ThreadSafeRandom = new ThreadLocal< Random >( valueFactory: () => new Random( Interlocked.Increment( ref seed ) ), trackAllValues: false );

        ///





        ///     A thread-local .
        ///
        public static Random Instance { get { return ThreadSafeRandom.Value; } }

        ///



        ///     Returns a random float between and .
        ///
        ///
        ///
        ///
        public static float NextFloat( float min = 0, float max = 1 ) { return ( float ) ( min + ( Instance.NextDouble() * ( max - min ) ) ); }


        ///



        ///     Generate a random number between and .
        ///
        /// The inclusive lower bound of the random number returned.
        /// The exclusive upper bound of the random number returned.
        ///
        public static int Next( int minValue, int maxValue ) { return Instance.Next( minValue: minValue, maxValue: maxValue ); }




1 comment:

Protiguous said...

Gah, blogspot is blarghing the code...