不多说,算法本身很简单,但是有一些要注意的地方,我写在注释里
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")
{
}
}
}