先生成1~1000的随机数
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 = ; i < ; i++)
{
int a = NextRandom(, , rng);
Console.WriteLine(string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), a.ToString().PadLeft(, '')));
}
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 = ; i < length; i++)
{
randomResult |= ((uint)randomNumber[i] << ((length - - i) * ));
}
return (int)(randomResult % numSeeds) + ;
}
}
注意将RNGCryptoServiceProvider定义为循环外的静态变量。
经测试,这样在并发不大的时候能保证订单号的唯一性。