Browse Source

feat: 优化蜂窝网络上下文生命周期管理 - 添加应用程序关闭时的资源释放 - 改进网络状态检查逻辑 - 统一状态管理方式

master
root 4 days ago
parent
commit
c61349421f
  1. 12
      CoreAgent.API/Program.cs
  2. 17
      CoreAgent.API/Startup.cs
  3. 144
      CoreAgent.Domain/Contexts/CellularNetworkContext.cs
  4. 17
      CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs

12
CoreAgent.API/Program.cs

@ -1,4 +1,5 @@
using CoreAgent.API; using CoreAgent.API;
using CoreAgent.Domain.Contexts;
using CoreAgent.Domain.Models.System; using CoreAgent.Domain.Models.System;
using CoreAgent.Infrastructure.Logging; using CoreAgent.Infrastructure.Logging;
using Serilog; using Serilog;
@ -33,8 +34,15 @@ try
var lifetime = app.Lifetime; var lifetime = app.Lifetime;
lifetime.ApplicationStopping.Register(() => lifetime.ApplicationStopping.Register(() =>
{ {
Log.Information("Application is stopping..."); try
// 在这里可以添加清理代码,比如关闭数据库连接等 {
CellularNetworkContext.Instance.Dispose();
Log.Information("蜂窝网络上下文已释放");
}
catch (Exception ex)
{
Log.Error(ex, "释放蜂窝网络上下文时发生错误");
}
}); });
lifetime.ApplicationStopped.Register(() => lifetime.ApplicationStopped.Register(() =>

17
CoreAgent.API/Startup.cs

@ -60,6 +60,21 @@ namespace CoreAgent.API
{ {
endpoints.MapControllers(); endpoints.MapControllers();
}); });
// 注册应用程序关闭事件
var lifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();
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); .AddJsonFile($"{configurationsDirectory}/netcommand.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
var networkCommandConfig = builder.Configuration.GetSection("networkCommand").Get<NetworkCommandConfig>(); var networkCommandConfig = builder.Configuration.GetSection("networkCommand").Get<NetworkCommandConfig>();
CellularNetworkContext.Instance.SetNetworkCommandConfig(networkCommandConfig); CellularNetworkContext.Instance.Initialize(networkCommandConfig);
// 添加配置 // 添加配置
builder.Services.Configure<AppSettings>(builder.Configuration); builder.Services.Configure<AppSettings>(builder.Configuration);

144
CoreAgent.Domain/Contexts/CellularNetworkContext.cs

@ -7,20 +7,51 @@ namespace CoreAgent.Domain.Contexts;
/// <summary> /// <summary>
/// 蜂窝网络领域上下文 /// 蜂窝网络领域上下文
/// </summary> /// </summary>
public class CellularNetworkContext public class CellularNetworkContext : IDisposable
{ {
private static readonly Lazy<CellularNetworkContext> _instance = new(() => new CellularNetworkContext()); private static readonly Lazy<CellularNetworkContext> _instance = new(() => new CellularNetworkContext());
private readonly object _lock = new(); private readonly object _lock = new();
private readonly Dictionary<string, CellularNetworkState> _networkStates = new(); private CellularNetworkState _networkState;
private NetworkCommandConfig _networkCommandConfig; private NetworkCommandConfig _networkCommandConfig;
private string NeConfigKey; private string _neConfigKey = string.Empty;
public CancellationTokenSource token = new CancellationTokenSource(); public CancellationTokenSource token = new CancellationTokenSource();
private bool _isDisposed;
private bool _isInitialized;
/// <summary> /// <summary>
/// 获取单例实例 /// 获取单例实例
/// </summary> /// </summary>
public static CellularNetworkContext Instance => _instance.Value; public static CellularNetworkContext Instance => _instance.Value;
private CellularNetworkContext() { } private CellularNetworkContext()
{
_isDisposed = false;
_isInitialized = false;
}
/// <summary>
/// 初始化上下文
/// </summary>
/// <param name="config">网络命令配置</param>
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;
}
}
/// <summary> /// <summary>
/// 设置网络命令配置 /// 设置网络命令配置
@ -30,6 +61,16 @@ public class CellularNetworkContext
{ {
lock (_lock) lock (_lock)
{ {
if (_isDisposed)
{
throw new ObjectDisposedException(nameof(CellularNetworkContext));
}
if (!_isInitialized)
{
throw new InvalidOperationException("上下文未初始化,请先调用Initialize方法");
}
_networkCommandConfig = config ?? throw new ArgumentNullException(nameof(config)); _networkCommandConfig = config ?? throw new ArgumentNullException(nameof(config));
} }
} }
@ -42,7 +83,17 @@ public class CellularNetworkContext
{ {
lock (_lock) 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) 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) lock (_lock)
{ {
return NeConfigKey; if (_isDisposed)
{
throw new ObjectDisposedException(nameof(CellularNetworkContext));
}
if (!_isInitialized)
{
throw new InvalidOperationException("上下文未初始化");
}
return _neConfigKey;
} }
} }
/// <summary> /// <summary>
/// 获取指定类型的命令配置 /// 获取指定类型的命令配置
/// </summary> /// </summary>
@ -87,44 +160,71 @@ public class CellularNetworkContext
} }
/// <summary> /// <summary>
/// 获取或创建网络状态 /// 获取网络状态
/// </summary> /// </summary>
/// <param name="NeConfigKey">网络接口名称</param>
/// <returns>网络状态</returns> /// <returns>网络状态</returns>
public CellularNetworkState GetOrCreateNetworkState(string NeConfigKey) public CellularNetworkState GetNetworkState()
{ {
lock (_lock) lock (_lock)
{ {
if (!_networkStates.TryGetValue(NeConfigKey, out var state)) if (_isDisposed)
{ {
state = new CellularNetworkState(NeConfigKey); throw new ObjectDisposedException(nameof(CellularNetworkContext));
_networkStates[NeConfigKey] = state;
} }
return state;
if (!_isInitialized)
{
throw new InvalidOperationException("上下文未初始化");
}
return _networkState ?? throw new InvalidOperationException("网络状态未初始化");
} }
} }
/// <summary> /// <summary>
/// 移除网络状态 /// 重置上下文状态
/// </summary> /// </summary>
/// <param name="NeConfigKey">网络接口名称</param> public void Reset()
public void RemoveNetworkState(string NeConfigKey)
{ {
lock (_lock) lock (_lock)
{ {
_networkStates.Remove(NeConfigKey); if (_isDisposed)
{
throw new ObjectDisposedException(nameof(CellularNetworkContext));
}
if (!_isInitialized)
{
return;
}
token.Cancel();
token = new CancellationTokenSource();
_networkState = new CellularNetworkState(_neConfigKey);
} }
} }
/// <summary> /// <summary>
/// 获取所有网络状态 /// 释放资源
/// </summary> /// </summary>
/// <returns>所有网络状态的集合</returns> public void Dispose()
public IReadOnlyCollection<CellularNetworkState> GetAllNetworkStates() {
if (_isDisposed)
{ {
return;
}
lock (_lock) lock (_lock)
{ {
return _networkStates.Values.ToList().AsReadOnly(); if (_isDisposed)
{
return;
}
token.Cancel();
token.Dispose();
_isInitialized = false;
_isDisposed = true;
} }
} }
} }

17
CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs

@ -80,12 +80,12 @@ public class CellularNetworkService : ICellularNetworkService
string NeConfigKey = _context.GetNeConfigKey(); string NeConfigKey = _context.GetNeConfigKey();
try try
{ {
// 1. 检查网络状态 // 1. 检查网络状态
var state = _context.GetOrCreateNetworkState(NeConfigKey); var state = _context.GetNetworkState();
if (!state.IsInitialized) if (state.CurrentStatus == NetworkStatus.Disconnected || state.CurrentStatus == NetworkStatus.Unknown)
{ {
_logger.LogWarning("蜂窝网络未初始化,无需停止"); _logger.LogWarning("蜂窝网络已经处于断开或未知状态,无需停止");
_context.Reset(); // 即使不需要停止,也重置状态
return true; return true;
} }
@ -119,6 +119,9 @@ public class CellularNetworkService : ICellularNetworkService
// 5. 更新状态 // 5. 更新状态
state.MarkAsStopped(); state.MarkAsStopped();
_logger.LogInformation($"蜂窝网络 {NeConfigKey} 停止成功"); _logger.LogInformation($"蜂窝网络 {NeConfigKey} 停止成功");
// 6. 重置上下文
_context.Reset();
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
@ -139,10 +142,10 @@ public class CellularNetworkService : ICellularNetworkService
} }
// 2. 检查网络状态 // 2. 检查网络状态
var state = _context.GetOrCreateNetworkState(key); var state = _context.GetNetworkState();
if (state.IsInitialized) if (state.CurrentStatus == NetworkStatus.Connected)
{ {
_logger.LogWarning("蜂窝网络已经初始化,不能重复启动"); _logger.LogWarning("蜂窝网络已经处于连接状态,不能重复启动");
return false; return false;
} }

Loading…
Cancel
Save