コード例 #1
0
        public static void TestSnowflake()
        {
            var array = new long[1000];

            Parallel.For(0, 1000, i => { array[i] = SnowFlake.Instance().NextId(); });
            Console.WriteLine("Distinct count:" + array.Distinct().Count());
            for (int i = 0; i < array.Length; i++)
            {
                Console.WriteLine(array[i]);
            }
        }
コード例 #2
0
        public static SnowFlake Instance()
        {
            lock (SnowflakeLock)
            {
                if (_snowflake != null)
                {
                    return(_snowflake);
                }
                var random = new Random();
                if (!int.TryParse(Environment.GetEnvironmentVariable("SF_MACHINEID", EnvironmentVariableTarget.Machine), out var machineId))
                {
                    machineId = random.Next((int)MaxMachineCount);
                }

                if (!int.TryParse(Environment.GetEnvironmentVariable("SF_DATACENTERID", EnvironmentVariableTarget.Machine), out var datacenterId))
                {
                    datacenterId = random.Next((int)MaxDatacenterCount);
                }

                return(_snowflake = new SnowFlake(machineId, datacenterId));
            }
        }