1
This commit is contained in:
@@ -13,35 +13,44 @@ 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();
|
||||
public EntitiesService(ILogger<EntitiesService> logger, IFixedTicker ticker)
|
||||
{
|
||||
_count++;
|
||||
|
||||
_logger = logger;
|
||||
_ticker = ticker;
|
||||
|
||||
_ticker.Add(OnTick);
|
||||
}
|
||||
|
||||
private void OnTick(float obj)
|
||||
{
|
||||
while (OnAddQueue.TryDequeue(out var entity))
|
||||
{
|
||||
OnAdd?.Invoke(entity);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public bool UnRegister(IEntity entity)
|
||||
{
|
||||
if (!Entities.TryRemove(entity.Id, out _)) return false;
|
||||
OnRemove?.Invoke(entity);
|
||||
OnRemove?.Invoke(entity);
|
||||
return true;
|
||||
}
|
||||
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
|
||||
@@ -262,6 +271,8 @@ namespace BITKit.Entities
|
||||
_logger.LogInformation($"已释放,还剩{_count}个实例");
|
||||
|
||||
_cancellationTokenSource?.Dispose();
|
||||
|
||||
_ticker.Remove(OnTick);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user