using CoreAgent.WebSocketTransport.Interfaces; using CoreAgent.WebSocketTransport.Models; using Microsoft.Extensions.Logging; namespace CoreAgent.WebSocketTransport.Services; /// /// 消息通道管理器实现 /// 单一职责:管理所有消息通道 /// public class MessageChannelManager : IMessageChannelManager { private readonly ILogger _logger; private volatile bool _disposed; private readonly object _disposeLock = new object(); public IMessageChannel SendChannel { get; } public IMessageChannel ReceiveChannel { get; } public IMessageChannel PriorityChannel { get; } /// /// 构造函数 /// /// 日志记录器 /// 发送通道容量 /// 接收通道容量 /// 优先级通道容量 public MessageChannelManager( ILogger logger, int sendChannelCapacity = 1000, int receiveChannelCapacity = 1000, int priorityChannelCapacity = 100) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); try { SendChannel = new ChannelMessageChannel(sendChannelCapacity); ReceiveChannel = new ChannelMessageChannel(receiveChannelCapacity); PriorityChannel = new ChannelMessageChannel(priorityChannelCapacity); _logger.LogInformation("消息通道管理器已创建 - 发送通道容量: {SendCapacity}, 接收通道容量: {ReceiveCapacity}, 优先级通道容量: {PriorityCapacity}", sendChannelCapacity, receiveChannelCapacity, priorityChannelCapacity); } catch (Exception ex) { _logger.LogError(ex, "创建消息通道管理器失败"); throw; } } /// /// 获取通道状态信息 /// public ChannelStatusInfo GetStatusInfo() { ThrowIfDisposed(); try { return new ChannelStatusInfo { SendChannelCount = SendChannel.Count, ReceiveChannelCount = ReceiveChannel.Count, PriorityChannelCount = PriorityChannel.Count, SendChannelCapacity = SendChannel.Capacity, ReceiveChannelCapacity = ReceiveChannel.Capacity, PriorityChannelCapacity = PriorityChannel.Capacity, SendChannelCompleted = SendChannel.IsCompleted, ReceiveChannelCompleted = ReceiveChannel.IsCompleted, PriorityChannelCompleted = PriorityChannel.IsCompleted }; } catch (Exception ex) { _logger.LogError(ex, "获取通道状态信息失败"); throw; } } /// /// 清空所有通道 /// public void ClearAllChannels() { ThrowIfDisposed(); try { SendChannel.Clear(); ReceiveChannel.Clear(); PriorityChannel.Clear(); _logger.LogInformation("所有通道已清空"); } catch (Exception ex) { _logger.LogError(ex, "清空通道失败"); throw; } } /// /// 完成所有通道 /// public void CompleteAllChannels() { ThrowIfDisposed(); try { SendChannel.Complete(); ReceiveChannel.Complete(); PriorityChannel.Complete(); _logger.LogInformation("所有通道已完成"); } catch (Exception ex) { _logger.LogError(ex, "完成通道失败"); throw; } } /// /// 释放资源 /// public void Dispose() { lock (_disposeLock) { if (!_disposed) { _disposed = true; try { // 先完成所有通道 CompleteAllChannels(); // 然后释放通道资源 SendChannel?.Dispose(); ReceiveChannel?.Dispose(); PriorityChannel?.Dispose(); _logger.LogInformation("消息通道管理器已释放"); } catch (Exception ex) { _logger.LogError(ex, "释放消息通道管理器时发生异常"); } GC.SuppressFinalize(this); } } } /// /// 检查是否已释放 /// private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(MessageChannelManager)); } } }