1
This commit is contained in:
@@ -13,28 +13,49 @@ namespace BITKit.Entities
|
||||
public class EntitiesService:IEntitiesService,IDisposable
|
||||
{
|
||||
private readonly ILogger<EntitiesService> _logger;
|
||||
|
||||
private readonly IFixedTicker _ticker;
|
||||
private static int _count;
|
||||
public EntitiesService()
|
||||
{
|
||||
_count++;
|
||||
}
|
||||
|
||||
public EntitiesService(ILogger<EntitiesService> logger)
|
||||
private static readonly ConcurrentQueue<IEntity> OnAddQueue = new();
|
||||
private static ConcurrentDictionary<int, HashSet<int>> TypeCaches = new();
|
||||
public EntitiesService(ILogger<EntitiesService> logger, IFixedTicker ticker)
|
||||
{
|
||||
if (_count > 0)
|
||||
{
|
||||
throw new MulticastNotSupportedException();
|
||||
}
|
||||
_count++;
|
||||
|
||||
_logger = logger;
|
||||
_ticker = ticker;
|
||||
|
||||
_ticker.Add(OnTick);
|
||||
}
|
||||
|
||||
private void OnTick(float obj)
|
||||
{
|
||||
while (OnAddQueue.TryDequeue(out var entity))
|
||||
{
|
||||
OnAdd?.Invoke(entity);
|
||||
|
||||
foreach (var serviceDescriptor in entity.ServiceCollection)
|
||||
{
|
||||
var typeHash = serviceDescriptor.ServiceType.GetHashCode();
|
||||
var hashSet = TypeCaches.GetOrCreate(typeHash);
|
||||
hashSet.Add(entity.Id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static readonly ConcurrentDictionary<int, IEntity> Entities = new();
|
||||
public event Action<IEntity> OnAdd;
|
||||
public event Action<IEntity> OnRemove;
|
||||
IEntity[] IEntitiesService.Entities => Entities.Values.ToArray();
|
||||
IReadOnlyDictionary<int, IEntity> IEntitiesService.Entities => Entities;
|
||||
public bool Register(IEntity entity)
|
||||
{
|
||||
if (!Entities.TryAdd(entity.Id, entity)) return false;
|
||||
OnAdd?.Invoke(entity);
|
||||
OnAddQueue.Enqueue(entity);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -42,8 +63,17 @@ namespace BITKit.Entities
|
||||
{
|
||||
if (!Entities.TryRemove(entity.Id, out _)) return false;
|
||||
OnRemove?.Invoke(entity);
|
||||
|
||||
foreach (var serviceDescriptor in entity.ServiceCollection)
|
||||
{
|
||||
var typeHash = serviceDescriptor.ServiceType.GetHashCode();
|
||||
var hashSet = TypeCaches.GetOrCreate(typeHash);
|
||||
hashSet.Remove(entity.Id);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
|
||||
private readonly CancellationTokenSource _cancellationTokenSource = new();
|
||||
public IEntity Get(int id)
|
||||
@@ -262,6 +292,8 @@ namespace BITKit.Entities
|
||||
_logger.LogInformation($"已释放,还剩{_count}个实例");
|
||||
|
||||
_cancellationTokenSource?.Dispose();
|
||||
|
||||
_ticker.Remove(OnTick);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user