生成数据库自增不重复ID的方法
Posted hanstar
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生成数据库自增不重复ID的方法相关的知识,希望对你有一定的参考价值。
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; } } } }
以上是关于生成数据库自增不重复ID的方法的主要内容,如果未能解决你的问题,请参考以下文章