C# 对象UID分配

不多说,算法本身很简单,但是有一些要注意的地方,我写在注释里

using System.Collections.Generic;
using System.Security.Cryptography;

namespace AirFramework
{
	//注意最大数量是int.MaxValue,而不是long.MaxValue
    public class UIDGenerator
    {
    	//用于存储存活的UID
        private readonly HashSet<long> _pool;
        //当前UID位置
        private long _pointer = 0;
		
		//初始化带有一个适当的初始容量可以提高性能,但是无关紧要
        public UIDGenerator(int defaultCount = 0)
        {
            _pool = new HashSet<long>(defaultCount);
        }

        /// <summary>
        /// 存活的ID数量
        /// </summary>
        public int SurvivalCapacity => _pool.Count;

        /// <summary>
        /// 从生成器申请ID
        /// </summary>
        /// <returns></returns>
        public long Allocate()
        {
            if(SurvivalCapacity>=int.MaxValue) throw new IDOverflowException();
            //使用while在ulong溢出时不会导致深循环,溢出时全部ID接近于MAX,突然重置为0后一般在极少的循环
            //次数内即可找到未占用的ID值,即时有少量的长期占用区域,也可以被快速跳过
            while (_pool.Contains(_pointer++))
            {
                if (_pointer == long.MaxValue) _pointer = 0;
            }
            _pool.Add(_pointer);
            return _pointer;
        }

        /// <summary>
        /// 将ID释放回生成器,注意这个步骤是必要的,否则终有一刻ID将会因为耗尽无法生成
        /// </summary>
        /// <param name="id"></param>
        public void Release(long id)
        {
            _pool.Remove(id);
        }

        /// <summary>
        /// 强制清空ID占用,注意这个操作可能导致ID重复发生不可挽回的后果
        /// </summary>
        public void ForceReleaseAll()
        {
            _pool.Clear();
        }
    }


    public class IDOverflowException:System.Exception
    { 
        public IDOverflowException() :base($"For each generator, the maximum number of IDs that exist simultaneously is {int.MaxValue}, please check if there are any IDs that have not been released") 
        {
            
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YUE ZHEN PENG

码字不易,如果你想请我喝杯果汁

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值