diff --git a/CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs b/CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs index ef8e3c6..ac5f0a2 100644 --- a/CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs +++ b/CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs @@ -264,6 +264,16 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable /// 释放资源 /// public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// 释放资源 + /// + /// 是否正在释放托管资源 + protected virtual void Dispose(bool disposing) { if (_isDisposed) { @@ -277,10 +287,39 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable return; } - _token?.Cancel(); - _token?.Dispose(); + if (disposing) + { + try + { + if (_token != null) + { + if (!_token.IsCancellationRequested) + { + _token.Cancel(); + } + _token.Dispose(); + } + } + catch (ObjectDisposedException) + { + // 忽略已释放的异常 + } + catch (Exception) + { + // 记录其他异常 + } + } + _isInitialized = false; _isDisposed = true; } } + + /// + /// 析构函数 + /// + ~CellularNetworkContext() + { + Dispose(false); + } } \ No newline at end of file