namespace ConsoleApp1 { class Program { static void Main(string[] args) { var list = new HashSet<string>(101); for (int i = 0; i < 100; i++) { var task = Task.Factory.StartNew((m => { var id = McidGenerator.NewMcid(); list.Add(id); Console.WriteLine($"序号:{(int)m + 1} 线程ID:{Thread.CurrentThread.ManagedThreadId} 生成的MCID:{id}"); }), i); } Thread.Sleep(10000); var n = 1; foreach (var li in list.OrderBy(i=>i)) { Console.WriteLine($"序号:{(int)n + 1} 生成的MCID:{li}"); n++; } Console.ReadLine(); } } public static class McidGenerator { private const int MaxId = 9; private static bool _allNew = true; private static int _incrementId = 0; private static DateTimeOffset _current = DateTimeOffset.Now; private static readonly object SequenceLock = new object(); public static string NewMcid() { lock (SequenceLock) { var now = DateTimeOffset.Now; if (_allNew) { _allNew = false; _current = now; return now.ToString("yyyyMMddHHmmssfffff") + _incrementId; } if (Convert.ToDateTime(_current.ToString("yyyy-MM-dd HH:mm:ss.fffff")) == Convert.ToDateTime(now.ToString("yyyy-MM-dd HH:mm:ss.fffff"))) { _incrementId++; _current = now; return now.ToString("yyyyMMddHHmmssfffff") + _incrementId; } _incrementId++; _incrementId = _incrementId > MaxId ? 0 : _incrementId; _current = now; return now.ToString("yyyyMMddHHmmssfffff") + _incrementId; } } } }