Browse Source

修复 StopAllClients 问题

feature/protocol-log-Perfect
root 3 days ago
parent
commit
8c7ebad2ff
  1. 9
      CoreAgent.Infrastructure/Services/Network/ProtocolWsClientManager.cs
  2. 56
      modify.md

9
CoreAgent.Infrastructure/Services/Network/ProtocolWsClientManager.cs

@ -212,7 +212,7 @@ namespace CoreAgent.Infrastructure.Services.Network
var client = kvp.Value;
var wasConnected = client.IsConnected;
client.Stop();
client.Dispose();
stoppedCount++;
// 检查连接状态
@ -231,8 +231,11 @@ namespace CoreAgent.Infrastructure.Services.Network
}
}
var allDisconnected = disconnectedCount == _clients.Count;
_logger.LogInformation("协议客户端停止完成 - 成功: {StoppedCount}, 失败: {FailedCount}, 已断开: {DisconnectedCount}, 全部断开: {AllDisconnected}",
// 移除所有客户端条目,确保下次StartAllClients会创建新实例
_clients.Clear();
var allDisconnected = disconnectedCount == stoppedCount;
_logger.LogInformation("协议客户端停止完成 - 成功: {StoppedCount}, 失败: {FailedCount}, 已断开: {DisconnectedCount}, 全部断开: {AllDisconnected}, 已清空客户端列表",
stoppedCount, failedCount, disconnectedCount, allDisconnected);
return allDisconnected;

56
modify.md

@ -2,6 +2,62 @@
## 2025-01-02
### ProtocolWsClientManager.StopAllClients方法移除_clients条目
**修改时间**: 2025年1月2日
**修改文件**:
- `CoreAgent.Infrastructure/Services/Network/ProtocolWsClientManager.cs`
**修改内容**:
1. **问题描述**:
- `StopAllClients` 方法停止所有协议客户端后,`_clients` 字典中仍然保留客户端条目
- 导致下次调用 `StartAllClients` 时会检查到已存在的客户端,不会创建新的 `ProtocolWsClient` 实例
- 需要确保每次 `StartAllClients` 都创建新的客户端实例
2. **修复方案**:
- 在 `StopAllClients` 方法中添加 `_clients.Clear()` 调用
- 移除所有客户端条目,确保下次启动时创建新实例
- 修改返回值计算逻辑,使用 `stoppedCount` 而不是 `_clients.Count`
- 添加日志记录,说明已清空客户端列表
3. **具体修改**:
```csharp
// 修改前
var allDisconnected = disconnectedCount == _clients.Count;
_logger.LogInformation("协议客户端停止完成 - 成功: {StoppedCount}, 失败: {FailedCount}, 已断开: {DisconnectedCount}, 全部断开: {AllDisconnected}",
stoppedCount, failedCount, disconnectedCount, allDisconnected);
// 修改后
// 移除所有客户端条目,确保下次StartAllClients会创建新实例
_clients.Clear();
var allDisconnected = disconnectedCount == stoppedCount;
_logger.LogInformation("协议客户端停止完成 - 成功: {StoppedCount}, 失败: {FailedCount}, 已断开: {DisconnectedCount}, 全部断开: {AllDisconnected}, 已清空客户端列表",
stoppedCount, failedCount, disconnectedCount, allDisconnected);
```
4. **设计优势**:
- **实例隔离**: 确保每次启动都创建新的协议客户端实例
- **资源清理**: 完全清理客户端引用,避免内存泄漏
- **状态重置**: 确保客户端管理器状态完全重置
- **日志完整**: 记录清空操作,便于调试和监控
- **逻辑正确**: 返回值计算基于实际停止的客户端数量
5. **修复的关键问题**:
- **实例复用**: 避免复用已停止的客户端实例
- **状态污染**: 防止旧实例状态影响新启动的客户端
- **资源管理**: 确保客户端资源完全释放
- **启动逻辑**: 保证 `StartAllClients` 每次都创建新实例
**影响范围**:
- 协议客户端管理器的生命周期管理
- 客户端实例的创建和销毁逻辑
- 资源清理和内存管理
- 网络启动流程的稳定性
## 2025-01-02
### WebSocketConnection.CloseAsync方法添加跟踪日志
**修改时间**: 2025年1月2日

Loading…
Cancel
Save