From c61349421f2524a5834cc713bf4dc6905c2e3551 Mon Sep 17 00:00:00 2001 From: root <295172551@qq.com> Date: Sat, 14 Jun 2025 02:48:55 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=E8=9C=82=E7=AA=9D?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E4=B8=8A=E4=B8=8B=E6=96=87=E7=94=9F=E5=91=BD?= =?UTF-8?q?=E5=91=A8=E6=9C=9F=E7=AE=A1=E7=90=86=20-=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E7=A8=8B=E5=BA=8F=E5=85=B3=E9=97=AD=E6=97=B6?= =?UTF-8?q?=E7=9A=84=E8=B5=84=E6=BA=90=E9=87=8A=E6=94=BE=20-=20=E6=94=B9?= =?UTF-8?q?=E8=BF=9B=E7=BD=91=E7=BB=9C=E7=8A=B6=E6=80=81=E6=A3=80=E6=9F=A5?= =?UTF-8?q?=E9=80=BB=E8=BE=91=20-=20=E7=BB=9F=E4=B8=80=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CoreAgent.API/Program.cs | 12 +- CoreAgent.API/Startup.cs | 17 +- .../Contexts/CellularNetworkContext.cs | 146 +++++++++++++++--- .../Network/CellularNetworkService.cs | 17 +- 4 files changed, 159 insertions(+), 33 deletions(-) diff --git a/CoreAgent.API/Program.cs b/CoreAgent.API/Program.cs index e4938e8..979a6b1 100644 --- a/CoreAgent.API/Program.cs +++ b/CoreAgent.API/Program.cs @@ -1,4 +1,5 @@ using CoreAgent.API; +using CoreAgent.Domain.Contexts; using CoreAgent.Domain.Models.System; using CoreAgent.Infrastructure.Logging; using Serilog; @@ -33,8 +34,15 @@ try var lifetime = app.Lifetime; lifetime.ApplicationStopping.Register(() => { - Log.Information("Application is stopping..."); - // 在这里可以添加清理代码,比如关闭数据库连接等 + try + { + CellularNetworkContext.Instance.Dispose(); + Log.Information("蜂窝网络上下文已释放"); + } + catch (Exception ex) + { + Log.Error(ex, "释放蜂窝网络上下文时发生错误"); + } }); lifetime.ApplicationStopped.Register(() => diff --git a/CoreAgent.API/Startup.cs b/CoreAgent.API/Startup.cs index 37d11f4..3e0c362 100644 --- a/CoreAgent.API/Startup.cs +++ b/CoreAgent.API/Startup.cs @@ -60,6 +60,21 @@ namespace CoreAgent.API { endpoints.MapControllers(); }); + + // 注册应用程序关闭事件 + var lifetime = app.ApplicationServices.GetRequiredService(); + lifetime.ApplicationStopping.Register(() => + { + try + { + CellularNetworkContext.Instance.Dispose(); + Log.Information("蜂窝网络上下文已释放"); + } + catch (Exception ex) + { + Log.Error(ex, "释放蜂窝网络上下文时发生错误"); + } + }); } } @@ -88,7 +103,7 @@ namespace CoreAgent.API .AddJsonFile($"{configurationsDirectory}/netcommand.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); var networkCommandConfig = builder.Configuration.GetSection("networkCommand").Get(); - CellularNetworkContext.Instance.SetNetworkCommandConfig(networkCommandConfig); + CellularNetworkContext.Instance.Initialize(networkCommandConfig); // 添加配置 builder.Services.Configure(builder.Configuration); diff --git a/CoreAgent.Domain/Contexts/CellularNetworkContext.cs b/CoreAgent.Domain/Contexts/CellularNetworkContext.cs index 587992f..c9f1c88 100644 --- a/CoreAgent.Domain/Contexts/CellularNetworkContext.cs +++ b/CoreAgent.Domain/Contexts/CellularNetworkContext.cs @@ -7,20 +7,51 @@ namespace CoreAgent.Domain.Contexts; /// /// 蜂窝网络领域上下文 /// -public class CellularNetworkContext +public class CellularNetworkContext : IDisposable { private static readonly Lazy _instance = new(() => new CellularNetworkContext()); private readonly object _lock = new(); - private readonly Dictionary _networkStates = new(); + private CellularNetworkState _networkState; private NetworkCommandConfig _networkCommandConfig; - private string NeConfigKey; - public CancellationTokenSource token =new CancellationTokenSource(); + private string _neConfigKey = string.Empty; + public CancellationTokenSource token = new CancellationTokenSource(); + private bool _isDisposed; + private bool _isInitialized; + /// /// 获取单例实例 /// public static CellularNetworkContext Instance => _instance.Value; - private CellularNetworkContext() { } + private CellularNetworkContext() + { + _isDisposed = false; + _isInitialized = false; + } + + /// + /// 初始化上下文 + /// + /// 网络命令配置 + public void Initialize(NetworkCommandConfig config = null) + { + lock (_lock) + { + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } + + if (_isInitialized) + { + return; + } + + _networkState = new CellularNetworkState(_neConfigKey); + _networkCommandConfig = config; + _isInitialized = true; + } + } /// /// 设置网络命令配置 @@ -30,6 +61,16 @@ public class CellularNetworkContext { lock (_lock) { + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } + + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化,请先调用Initialize方法"); + } + _networkCommandConfig = config ?? throw new ArgumentNullException(nameof(config)); } } @@ -42,7 +83,17 @@ public class CellularNetworkContext { lock (_lock) { - return _networkCommandConfig ?? throw new InvalidOperationException("网络命令配置未初始化"); + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } + + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化"); + } + + return _networkCommandConfig ?? throw new InvalidOperationException("网络命令配置未设置"); } } @@ -50,7 +101,18 @@ public class CellularNetworkContext { lock (_lock) { - return NeConfigKey= key ?? throw new ArgumentNullException(nameof(key)); + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } + + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化"); + } + + _neConfigKey = key ?? throw new ArgumentNullException(nameof(key)); + return _neConfigKey; } } @@ -58,9 +120,20 @@ public class CellularNetworkContext { lock (_lock) { - return NeConfigKey; + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } + + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化"); + } + + return _neConfigKey; } } + /// /// 获取指定类型的命令配置 /// @@ -87,44 +160,71 @@ public class CellularNetworkContext } /// - /// 获取或创建网络状态 + /// 获取网络状态 /// - /// 网络接口名称 /// 网络状态 - public CellularNetworkState GetOrCreateNetworkState(string NeConfigKey) + public CellularNetworkState GetNetworkState() { lock (_lock) { - if (!_networkStates.TryGetValue(NeConfigKey, out var state)) + if (_isDisposed) { - state = new CellularNetworkState(NeConfigKey); - _networkStates[NeConfigKey] = state; + throw new ObjectDisposedException(nameof(CellularNetworkContext)); } - return state; + + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化"); + } + + return _networkState ?? throw new InvalidOperationException("网络状态未初始化"); } } /// - /// 移除网络状态 + /// 重置上下文状态 /// - /// 网络接口名称 - public void RemoveNetworkState(string NeConfigKey) + public void Reset() { lock (_lock) { - _networkStates.Remove(NeConfigKey); + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } + + if (!_isInitialized) + { + return; + } + + token.Cancel(); + token = new CancellationTokenSource(); + _networkState = new CellularNetworkState(_neConfigKey); } } /// - /// 获取所有网络状态 + /// 释放资源 /// - /// 所有网络状态的集合 - public IReadOnlyCollection GetAllNetworkStates() + public void Dispose() { + if (_isDisposed) + { + return; + } + lock (_lock) { - return _networkStates.Values.ToList().AsReadOnly(); + if (_isDisposed) + { + return; + } + + token.Cancel(); + token.Dispose(); + _isInitialized = false; + _isDisposed = true; } } } diff --git a/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs b/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs index f5fd078..5793065 100644 --- a/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs +++ b/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs @@ -80,12 +80,12 @@ public class CellularNetworkService : ICellularNetworkService string NeConfigKey = _context.GetNeConfigKey(); try { - // 1. 检查网络状态 - var state = _context.GetOrCreateNetworkState(NeConfigKey); - if (!state.IsInitialized) + var state = _context.GetNetworkState(); + if (state.CurrentStatus == NetworkStatus.Disconnected || state.CurrentStatus == NetworkStatus.Unknown) { - _logger.LogWarning("蜂窝网络未初始化,无需停止"); + _logger.LogWarning("蜂窝网络已经处于断开或未知状态,无需停止"); + _context.Reset(); // 即使不需要停止,也重置状态 return true; } @@ -119,6 +119,9 @@ public class CellularNetworkService : ICellularNetworkService // 5. 更新状态 state.MarkAsStopped(); _logger.LogInformation($"蜂窝网络 {NeConfigKey} 停止成功"); + + // 6. 重置上下文 + _context.Reset(); return true; } catch (Exception ex) @@ -139,10 +142,10 @@ public class CellularNetworkService : ICellularNetworkService } // 2. 检查网络状态 - var state = _context.GetOrCreateNetworkState(key); - if (state.IsInitialized) + var state = _context.GetNetworkState(); + if (state.CurrentStatus == NetworkStatus.Connected) { - _logger.LogWarning("蜂窝网络已经初始化,不能重复启动"); + _logger.LogWarning("蜂窝网络已经处于连接状态,不能重复启动"); return false; }