RNGCryptoServiceProvider generated order number

Mr. Cheng random number from 1 to 1,000

class Program
    {
        // Create a new instance of the RNGCryptoServiceProvider.  
        private static System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

        static void Main(string[] args)
        {
            for (int i = 0; i < 100; i++)
            {
                int a = NextRandom(1000, 1, rng);
                Console.WriteLine(string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), a.ToString().PadLeft(4, '0')));
            }
            Console.Read();
        }
        private static int NextRandom(int numSeeds, int length, System.Security.Cryptography.RNGCryptoServiceProvider rng)
        {
            // Create a byte array to hold the random value.  
            byte[] randomNumber = new byte[length];
            // Fill the array with a random value.  
            rng.GetBytes(randomNumber);
            // Convert the byte to an uint value to make the modulus operation easier.  
            uint randomResult = 0x0;
            for (int i = 0; i < length; i++)
            {
                randomResult |= ((uint)randomNumber[i] << ((length - 1 - i) * 8));
            }
            return (int)(randomResult % numSeeds) + 1;
        }
    }
View Code

Note RNGCryptoServiceProvider defines a static variable outside the loop.

After testing, so that when concurrent small to ensure the uniqueness of the order number.

Guess you like

Origin www.cnblogs.com/tylertang/p/11183303.html