十年河东,十年河西,莫欺少年穷
学无止境,精益求精
代码如下:
class Program { static int seed = 13; static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed))); public static int GetTid(int length = 6) { var maxLen = int.MaxValue.ToString().Length; if (length > maxLen) { return 0; } var TxID = Math.Abs(threadLocal.Value.Next() - Convert.ToInt32(DateTime.Now.ToString("HHmmssfff"))); var len = TxID.ToString().Length; if (len >= length) { return Convert.ToInt32(TxID.ToString().Substring(0, length)); } return new Random(seed).Next(Convert.ToInt32(Math.Pow(10, length - 1)), Convert.ToInt32(Math.Pow(10, length)) - 1); } public static void Main(string[] args) { for(var i = 0; i < 100; i++) { Console.WriteLine("四位数字为:" + GetTid(4)); } Console.ReadLine(); } }
核心代码:
var TxID = Math.Abs(threadLocal.Value.Next() - Convert.ToInt32(DateTime.Now.ToString("HHmmssfff")));
不信你看嘛
public static void Main(string[] args) { List<int> lst = new List<int>(); int Nm = 0; for(int i = 0; i < 5000; i++) { var s = GetTid(); if (lst.Contains(s)) { Nm++; Console.WriteLine("重复了"+Nm); } lst.Add(s); } Console.ReadLine(); }
六位数字,5000次数据生产 重复了36次
如何不限定长度,我们的测试如下:
class Program { static int seed = 13; static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed))); public static int GetTid() { var TxID = Math.Abs(threadLocal.Value.Next() - Convert.ToInt32(DateTime.Now.ToString("HHmmssfff"))); return TxID; } public static void Main(string[] args) { List<int> lst = new List<int>(); int Nm = 0; for(int i = 0; i < 50000; i++) { var s = GetTid(); if (lst.Contains(s)) { Nm++; Console.WriteLine("重复了"+Nm); } lst.Add(s); } Console.ReadLine(); } }
50000次仅仅重复了一次
@天才卧龙的博客