From 8aaef24b48c8b7e251239b5f6ebfe88fe328aa6a Mon Sep 17 00:00:00 2001 From: root <295172551@qq.com> Date: Sun, 15 Jun 2025 13:18:40 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=BD=91=E7=BB=9C=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E7=9B=91=E6=8E=A7=EF=BC=9A1.=20=E5=B0=86=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E7=B1=BB=E5=9E=8B=E5=8F=82=E6=95=B0=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E5=B8=83=E5=B0=94=E7=B1=BB=E5=9E=8B=202.=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=90=AF=E5=8A=A8=E5=92=8C=E5=81=9C=E6=AD=A2=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E7=9A=84=E6=A3=80=E6=9F=A5=E9=80=BB=E8=BE=91=203.=20=E6=94=B9?= =?UTF-8?q?=E8=BF=9B=E6=97=A5=E5=BF=97=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Network/INetworkStatusMonitor.cs | 3 +- .../Contexts/CellularNetworkContext.cs | 50 ++++++++++--- .../Network/CellularNetworkService.cs | 4 +- .../Services/Network/NetworkStatusMonitor.cs | 71 +++++++++++++------ 4 files changed, 97 insertions(+), 31 deletions(-) diff --git a/CoreAgent.Domain/Interfaces/Network/INetworkStatusMonitor.cs b/CoreAgent.Domain/Interfaces/Network/INetworkStatusMonitor.cs index 8e512ac..38be1ab 100644 --- a/CoreAgent.Domain/Interfaces/Network/INetworkStatusMonitor.cs +++ b/CoreAgent.Domain/Interfaces/Network/INetworkStatusMonitor.cs @@ -16,7 +16,8 @@ public interface INetworkStatusMonitor public Task CheckAllEndPointsStatusAsync( NetworkIPEndPointCollection endPoints, NetworkConfigType configType, - int? timeoutSeconds = null); + int? timeoutSeconds = null, + bool isStartOperation = true); /// /// 检查 RAN 端点状态 diff --git a/CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs b/CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs index ac5f0a2..094ce68 100644 --- a/CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs +++ b/CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs @@ -3,6 +3,7 @@ using CoreAgent.Domain.Interfaces.Network; using CoreAgent.Domain.Models.Network; using CoreAgent.Domain.Models.System; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Logging; namespace CoreAgent.Infrastructure.Contexts; @@ -21,6 +22,7 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable private bool _isInitialized; private readonly INetworkIPEndPointManager _networkIPEndPointManager; private NetworkConfigType _currentConfigType; + private readonly ILogger _logger; /// /// 获取取消令牌源 @@ -45,7 +47,8 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable public CellularNetworkContext( IOptions networkCommandConfig, IOptions appSettings, - INetworkIPEndPointManager networkIPEndPointManager) + INetworkIPEndPointManager networkIPEndPointManager, + ILogger logger) { _isDisposed = false; _isInitialized = false; @@ -53,6 +56,7 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable _networkCommandConfig = networkCommandConfig?.Value ?? throw new ArgumentNullException(nameof(networkCommandConfig)); _appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings)); _networkIPEndPointManager = networkIPEndPointManager ?? throw new ArgumentNullException(nameof(networkIPEndPointManager)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _currentConfigType = NetworkConfigType.None; } @@ -206,23 +210,53 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable { if (_isDisposed) { + _logger.LogWarning("尝试重置已释放的 CellularNetworkContext"); throw new ObjectDisposedException(nameof(CellularNetworkContext)); } if (!_isInitialized) { + _logger.LogInformation("CellularNetworkContext 未初始化,跳过重置操作"); return; } lock (_lock) { - _token.Cancel(); - _token = new CancellationTokenSource(); - _neConfigKey = string.Empty; - _isInitialized = false; - _networkState = new CellularNetworkState(string.Empty); - _networkIPEndPointManager.Clear(); - _currentConfigType = NetworkConfigType.None; + try + { + if (_token != null && !_token.IsCancellationRequested) + { + _logger.LogDebug("正在取消当前的 CancellationTokenSource"); + _token.Cancel(); + } + } + catch (ObjectDisposedException ex) + { + _logger.LogWarning(ex, "CancellationTokenSource 已被释放"); + } + catch (Exception ex) + { + _logger.LogError(ex, "取消操作时发生异常"); + } + finally + { + try + { + _token?.Dispose(); + _token = new CancellationTokenSource(); + _neConfigKey = string.Empty; + _isInitialized = false; + _networkState = new CellularNetworkState(string.Empty); + _networkIPEndPointManager.Clear(); + _currentConfigType = NetworkConfigType.None; + _logger.LogInformation("CellularNetworkContext 重置完成"); + } + catch (Exception ex) + { + _logger.LogError(ex, "重置 CellularNetworkContext 状态时发生异常"); + throw; + } + } } } diff --git a/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs b/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs index caacf82..7ba4af0 100644 --- a/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs +++ b/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs @@ -215,7 +215,7 @@ public class CellularNetworkService : ICellularNetworkService // 6. 检查网络端点连接状态 _logger.LogInformation("开始检查所有网络端点的连接状态"); - var statusCheckResult = await _statusMonitor.CheckAllEndPointsStatusAsync(endPoints, _context.CurrentConfigType); + var statusCheckResult = await _statusMonitor.CheckAllEndPointsStatusAsync(endPoints, _context.CurrentConfigType, isStartOperation:false); if (statusCheckResult.IsSuccess) { _logger.LogWarning("网络端点仍然处于连接状态,停止操作失败"); @@ -288,7 +288,7 @@ public class CellularNetworkService : ICellularNetworkService // 8. 检查网络端点连接状态 _logger.LogInformation("开始检查所有网络端点的连接状态"); - var statusCheckResult = await _statusMonitor.CheckAllEndPointsStatusAsync(endPoints, enableResult.ConfigType); + var statusCheckResult = await _statusMonitor.CheckAllEndPointsStatusAsync(endPoints, enableResult.ConfigType, isStartOperation:true); if (!statusCheckResult.IsSuccess) { var errorMessage = string.Join("; ", statusCheckResult.ErrorMessage); diff --git a/CoreAgent.Infrastructure/Services/Network/NetworkStatusMonitor.cs b/CoreAgent.Infrastructure/Services/Network/NetworkStatusMonitor.cs index 7423eb4..ee90caa 100644 --- a/CoreAgent.Infrastructure/Services/Network/NetworkStatusMonitor.cs +++ b/CoreAgent.Infrastructure/Services/Network/NetworkStatusMonitor.cs @@ -34,11 +34,13 @@ public class NetworkStatusMonitor : INetworkStatusMonitor /// 网络端点信息 /// 网络配置类型 /// 超时时间(秒),默认30秒 + /// 是否为启动操作,true表示启动操作,false表示停止操作 /// 检查结果 public async Task CheckAllEndPointsStatusAsync( NetworkIPEndPointCollection endPoints, NetworkConfigType configType, - int? timeoutSeconds = null) + int? timeoutSeconds = null, + bool isStartOperation = true) { var result = new NetworkStatusCheckResult(); var startTime = DateTime.Now; @@ -46,43 +48,72 @@ public class NetworkStatusMonitor : INetworkStatusMonitor try { - _logger.LogInformation("开始检查网络端点状态,配置类型: {ConfigType}, 超时时间: {TimeoutSeconds}秒", - configType, timeout.TotalSeconds); + _logger.LogInformation("开始检查网络端点状态,配置类型: {ConfigType}, 操作类型: {OperationType}, 超时时间: {TimeoutSeconds}秒", + configType, isStartOperation ? "Start" : "Stop", timeout.TotalSeconds); // 先执行一次检查 var checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType); - result.IsSuccess = checkResults.All(r => r.IsSuccess); - - // 如果检查失败,进入重试循环 - while (!result.IsSuccess && DateTime.Now - startTime < timeout) + + // 根据操作类型采用不同的检查策略 + if (isStartOperation) { - var failedEndpoints = checkResults.Where(r => !r.IsSuccess) - .Select(r => $"{r.ComAddr}: {r.ErrorMessage}"); - var errorMessage = string.Join("; ", failedEndpoints); - _logger.LogWarning("网络端点状态检查未通过,失败端点: {FailedEndpoints},将在1秒后重试,已耗时: {ElapsedTime}秒", - errorMessage, (DateTime.Now - startTime).TotalSeconds); + // Start 操作:所有端点必须成功 + result.IsSuccess = checkResults.All(r => r.IsSuccess); - await Task.Delay(1000); // 等待1秒后重试 + // 如果检查失败,进入重试循环 + while (!result.IsSuccess && DateTime.Now - startTime < timeout) + { + var failedEndpoints = checkResults.Where(r => !r.IsSuccess) + .Select(r => $"{r.ComAddr}: {r.ErrorMessage}"); + var errorMessage = string.Join("; ", failedEndpoints); + _logger.LogWarning("网络端点状态检查未通过,失败端点: {FailedEndpoints},将在1秒后重试,已耗时: {ElapsedTime}秒", + errorMessage, (DateTime.Now - startTime).TotalSeconds); + + await Task.Delay(1000); // 等待1秒后重试 + + // 重试检查 + checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType); + result.IsSuccess = checkResults.All(r => r.IsSuccess); + } + } + else + { + // Stop 操作:所有端点必须失败 + result.IsSuccess = checkResults.All(r => !r.IsSuccess); - // 重试检查 - checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType); - result.IsSuccess = checkResults.All(r => r.IsSuccess); + // 如果检查未失败,进入重试循环 + while (!result.IsSuccess && DateTime.Now - startTime < timeout) + { + var activeEndpoints = checkResults.Where(r => r.IsSuccess) + .Select(r => r.ComAddr); + var errorMessage = string.Join("; ", activeEndpoints); + _logger.LogWarning("网络端点仍然处于活动状态: {ActiveEndpoints},将在1秒后重试,已耗时: {ElapsedTime}秒", + errorMessage, (DateTime.Now - startTime).TotalSeconds); + + await Task.Delay(1000); // 等待1秒后重试 + + // 重试检查 + checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType); + result.IsSuccess = checkResults.All(r => !r.IsSuccess); + } } if (!result.IsSuccess) { result.ErrorMessage = new string[] { $"检查超时,已超过{timeout.TotalSeconds}秒" }; - _logger.LogWarning("网络端点状态检查超时,配置类型: {ConfigType}", configType); + _logger.LogWarning("网络端点状态检查超时,配置类型: {ConfigType}, 操作类型: {OperationType}", + configType, isStartOperation ? "Start" : "Stop"); } else { - _logger.LogInformation("网络端点状态检查成功,配置类型: {ConfigType}, 耗时: {ElapsedTime}秒", - configType, (DateTime.Now - startTime).TotalSeconds); + _logger.LogInformation("网络端点状态检查成功,配置类型: {ConfigType}, 操作类型: {OperationType}, 耗时: {ElapsedTime}秒", + configType, isStartOperation ? "Start" : "Stop", (DateTime.Now - startTime).TotalSeconds); } } catch (Exception ex) { - _logger.LogError(ex, "检查网络端点状态时发生错误,配置类型: {ConfigType}", configType); + _logger.LogError(ex, "检查网络端点状态时发生错误,配置类型: {ConfigType}, 操作类型: {OperationType}", + configType, isStartOperation ? "Start" : "Stop"); result.IsSuccess = false; result.ErrorMessage = new string[] { $"检查过程发生异常: {ex.Message}" }; }