• 生成数据库自增不重复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;
                }
            }
        }
    }
  • 相关阅读:
    Python实战之SocketServer模块
    CentOS出错You don't have permission to access on this server
    系统瓶颈分析
    loadrunner支持https协议的操作方法-经验总结
    Loadrunner上传与下载文件脚本
    Loadrunner之HTTP接口测试脚本实例
    Android界面性能调优手册
    Loadrunner11.0 录制手机App脚本的方法
    资源监控工具--spotlight
    Jmeter常见问题
  • 原文地址:https://www.cnblogs.com/hanstar/p/9901968.html
Copyright © 2020-2023  润新知