public class IDFactory
    {
        public IDFactory()
        {
            LoadIPGroup();
            InitMillisecond = (ulong)(DateTime.Now - DateTime.Parse("2000-1-1")).TotalMilliseconds;
            mWatch.Restart();
        }
        private ulong mCurrentMillisecond = 0;
        private byte mSeed;
        private System.Diagnostics.Stopwatch mWatch = new System.Diagnostics.Stopwatch();
        public void LoadIPGroup()
        {
            string hostName = Dns.GetHostName();
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);
            foreach (IPAddress ip in addressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    Group = (byte)(ip.Address >> 24);
                    break;
                }
            }
        }
        public byte Group
        {
            get;
            set;
        }
        private ulong InitMillisecond;
        public ulong Next()
        {
            ulong result=0;
            System.Threading.SpinLock slock = new System.Threading.SpinLock();
            bool gotLock = false;
            try
            {
                while (!gotLock)
                {
                    slock.Enter(ref gotLock);
                    if (gotLock)
                    {
                        ulong cms = (ulong)mWatch.Elapsed.TotalMilliseconds + InitMillisecond;
                        if (cms != mCurrentMillisecond)
                        {
                            mSeed = 0;
                            mCurrentMillisecond = cms;
                        }
                        result = ((ulong)Group << 58) | (mCurrentMillisecond << 8) | (ulong)mSeed;
                        mSeed++;
                    }
                }
            }
            finally
            {
                if (gotLock) slock.Exit();
            }
            return result;
        }
    }

关注微信公众号



相关文章