From 0cc83d0a71e1e4761f82913daf36154f68007ee8 Mon Sep 17 00:00:00 2001 From: sophelper <123211521@163.com> Date: Thu, 5 Nov 2026 21:40:01 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=BA=94=E7=94=A8=E9=80=80=E5=87=BA?= =?UTF-8?q?=E6=97=B6=E5=81=9C=E6=AD=A2=E9=87=87=E9=9B=86=E5=B9=B6=E6=8C=89?= =?UTF-8?q?=E9=A1=BA=E5=BA=8F=E9=87=8A=E6=94=BE=E7=9B=B8=E6=9C=BA=E5=92=8C?= =?UTF-8?q?=E6=8E=A8=E7=90=86=E8=B5=84=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 11 ++ src/SopHelper.App/App.xaml.cs | 26 ++++- .../VVMs/SopPage/SopPageViewModel.cs | 10 +- src/SopHelper.Engine/Camera/CameraService.cs | 73 ++++++++++--- .../Pipeline/DetectionPipeline.cs | 3 + tests/ShutdownSmoke/Program.cs | 102 ++++++++++++++++++ tests/ShutdownSmoke/ShutdownSmoke.csproj | 13 +++ 7 files changed, 219 insertions(+), 19 deletions(-) create mode 100644 tests/ShutdownSmoke/Program.cs create mode 100644 tests/ShutdownSmoke/ShutdownSmoke.csproj diff --git a/README.md b/README.md index f3aaa3a..a8da659 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,17 @@ dotnet build SopHelper.slnx 灰度、Bayer、RGB、YUV 等格式转换后再交给管线。SDK 缓冲在复制后立即归还。 未安装 MVS 时日志提示原因,UVC 仍可使用。此功能针对工业相机,不包含安防摄像头 RTSP。 +应用退出统一释放相机,再释放推理管线,不依赖页面的 `Destroy()`。 +退出时等待尚未完成的设备操作及采集线程,归还缓冲、关闭设备并反初始化 MVS。 + +退出回归检查(不创建窗口,执行正式 WPF 退出链路): + +```bash +dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj +# 连接现场海康、收到视频帧后直接退出,并在同一进程中验证设备可重新打开 +dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj -- --hardware +``` + ## 配方 `configs/sop/*.yaml`,写好的例子见 `configs/sop/demo.yaml`。 diff --git a/src/SopHelper.App/App.xaml.cs b/src/SopHelper.App/App.xaml.cs index d817d4d..9a80978 100644 --- a/src/SopHelper.App/App.xaml.cs +++ b/src/SopHelper.App/App.xaml.cs @@ -20,6 +20,9 @@ namespace SopHelper; /// public partial class App { + private ICameraService? _camera; + private DetectionPipeline? _pipeline; + /// /// 注册应用程序所需的类型和服务 /// @@ -47,8 +50,11 @@ public partial class App // 引擎层三件套。它们在 SopHelper.Engine 程序集里,上面的 [Model] 反射扫描只覆盖本程序集, // 所以必须显式注册,否则 SOP 页 ViewModel 的构造注入解析不出来。 - _ = containerRegistry.RegisterSingleton(); - _ = containerRegistry.RegisterSingleton(); + // 共享硬件和推理由应用持有;页面销毁和容器回收不能代替应用退出清理。 + _camera = new CameraService(); + _pipeline = new DetectionPipeline(_camera); + containerRegistry.RegisterInstance(_camera); + containerRegistry.RegisterInstance(_pipeline); _ = containerRegistry.RegisterSingleton(); // ViewModel 工厂默认走容器解析,带构造注入的 ViewModel 必须先注册 @@ -91,6 +97,22 @@ public partial class App return window; } + protected override void OnExit(ExitEventArgs e) + { + try + { + // Dispose 等待采集线程退出、归还缓冲并关闭设备,然后才能释放推理模型。 + try { _camera?.Dispose(); } + catch (Exception ex) { Log(ex, "Exit.Camera"); } + try { _pipeline?.Dispose(); } + catch (Exception ex) { Log(ex, "Exit.Pipeline"); } + } + finally + { + base.OnExit(e); + } + } + /// /// 自动寻找ViewModel并绑定到View,要求ViewModel命名为View的全名加上ViewModel,比如MainWindow的ViewModel命名为MainWindowViewModel /// diff --git a/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs index f451c87..a320ce4 100644 --- a/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs +++ b/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs @@ -41,6 +41,7 @@ public class SopPageViewModel : ViewModelBase private readonly object _frameLock = new(); private Mat? _pending; + private bool _destroyed; /// 最近一次处理过的帧(快照按钮存盘用,由推理线程写入) private FrameResult? _lastFrame; @@ -297,10 +298,10 @@ public class SopPageViewModel : ViewModelBase /// private void OnCameraFrame(CameraFrame frame) { - var clone = frame.Bgr.Clone(); - lock (_frameLock) { + if (_destroyed) return; + var clone = frame.Bgr.Clone(); var old = _pending; _pending = clone; old?.Dispose(); @@ -333,15 +334,16 @@ public class SopPageViewModel : ViewModelBase public override void Destroy() { _renderTimer.Stop(); + _camera.FrameArrived -= OnCameraFrame; lock (_frameLock) { + _destroyed = true; _pending?.Dispose(); _pending = null; } - _pipeline.Dispose(); - _camera.Dispose(); + // 相机与推理管线是应用级单例,由 App.OnExit 按顺序统一释放。 base.Destroy(); } diff --git a/src/SopHelper.Engine/Camera/CameraService.cs b/src/SopHelper.Engine/Camera/CameraService.cs index c0a94e9..7204f35 100644 --- a/src/SopHelper.Engine/Camera/CameraService.cs +++ b/src/SopHelper.Engine/Camera/CameraService.cs @@ -6,6 +6,8 @@ public sealed class CameraService : ICameraService private readonly ICameraService _uvc = new UvcCameraService(); private readonly ICameraService _hik = new HikvisionCameraService(); private ICameraService? _active; + private readonly SemaphoreSlim _operations = new(1, 1); + private bool _disposed; public CameraService() { @@ -25,26 +27,71 @@ public sealed class CameraService : ICameraService public async Task> EnumerateAsync() { - // 优先展示海康;没有安装 MVS 时仍可使用 UVC。 - var cameras = await _hik.EnumerateAsync(); - cameras.AddRange(await _uvc.EnumerateAsync()); - return cameras; + await _operations.WaitAsync().ConfigureAwait(false); + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + // 优先展示海康;没有安装 MVS 时仍可使用 UVC。 + var cameras = await _hik.EnumerateAsync().ConfigureAwait(false); + cameras.AddRange(await _uvc.EnumerateAsync().ConfigureAwait(false)); + return cameras; + } + finally { _operations.Release(); } } public async Task ConnectAsync(CameraInfo camera) { - if (_active is not null) await Task.Run(_active.Disconnect); - _active = camera.Kind == CameraKind.Hikvision ? _hik : _uvc; - return await _active.ConnectAsync(camera); + await _operations.WaitAsync().ConfigureAwait(false); + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_active is not null) await Task.Run(_active.Disconnect).ConfigureAwait(false); + _active = camera.Kind == CameraKind.Hikvision ? _hik : _uvc; + return await _active.ConnectAsync(camera).ConfigureAwait(false); + } + finally { _operations.Release(); } + } + + public async Task StartAsync() + { + await _operations.WaitAsync().ConfigureAwait(false); + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + return _active is not null && await _active.StartAsync().ConfigureAwait(false); + } + finally { _operations.Release(); } + } + + public void Stop() + { + _operations.Wait(); + try { if (!_disposed) _active?.Stop(); } + finally { _operations.Release(); } + } + + public void Disconnect() + { + _operations.Wait(); + try { if (!_disposed) _active?.Disconnect(); } + finally { _operations.Release(); } } - public Task StartAsync() => _active?.StartAsync() ?? Task.FromResult(false); - public void Stop() => _active?.Stop(); - public void Disconnect() => _active?.Disconnect(); public void Dispose() { - _uvc.Dispose(); - _hik.Dispose(); - _active = null; + // 与尚未完成的连接/枚举串行;退出后不允许后台任务重新打开相机。 + _operations.Wait(); + try + { + if (_disposed) return; + _disposed = true; + try { _uvc.Dispose(); } + finally + { + try { _hik.Dispose(); } + finally { _active = null; } + } + } + finally { _operations.Release(); } } } diff --git a/src/SopHelper.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.Engine/Pipeline/DetectionPipeline.cs index 93dfa76..8e9db7d 100644 --- a/src/SopHelper.Engine/Pipeline/DetectionPipeline.cs +++ b/src/SopHelper.Engine/Pipeline/DetectionPipeline.cs @@ -50,6 +50,7 @@ public class DetectionPipeline : IDisposable private PipelineOptions _options = new(); private long _seen; private long _processed; + private bool _disposed; /// 管线就绪度(缺哪个模型就在这里报告,界面据此提示) public List Warnings { get; private set; } = []; @@ -186,6 +187,8 @@ public class DetectionPipeline : IDisposable /// public void Dispose() { + if (_disposed) return; + _disposed = true; _camera.FrameArrived -= OnFrame; _yolo.Dispose(); _hand.Dispose(); diff --git a/tests/ShutdownSmoke/Program.cs b/tests/ShutdownSmoke/Program.cs new file mode 100644 index 0000000..0e322f7 --- /dev/null +++ b/tests/ShutdownSmoke/Program.cs @@ -0,0 +1,102 @@ +using System.Windows; +using Prism.DryIoc; +using Prism.Ioc; +using SopHelper.Engine.Camera; +using SopHelper.Engine.Pipeline; + +internal static class Program +{ + [STAThread] + private static int Main(string[] args) + { + var app = new ShutdownProbe(args.Contains("--hardware")); + var result = app.Run(); + if (result != 0) return result; + return app.VerifyAfterExitAsync().GetAwaiter().GetResult(); + } +} + +/// 不创建窗口;使用正式服务注册及 WPF Shutdown → App.OnExit 链路。 +internal sealed class ShutdownProbe(bool hardware) : SopHelper.App +{ + private ICameraService _camera = null!; + private DetectionPipeline _pipeline = null!; + private CameraInfo? _selected; + private bool _exitObserved; + + protected override async void OnStartup(StartupEventArgs e) + { + ShutdownMode = ShutdownMode.OnExplicitShutdown; + var registry = new DryIocContainerExtension(); + RegisterTypes(registry); + _camera = registry.Resolve(); + _pipeline = registry.Resolve(); + _camera.Error += message => Console.WriteLine(message); + Exit += (_, _) => + { + // App.OnExit 必须在调用 WPF 的 Exit 事件之前完成释放。 + _exitObserved = true; + if (_camera.IsConnected || _camera.IsGrabbing) + throw new InvalidOperationException("WPF Exit 时相机仍在连接/采集"); + }; + + try + { + if (hardware) + { + _selected = (await _camera.EnumerateAsync()).FirstOrDefault(c => c.Kind == CameraKind.Hikvision) + ?? throw new InvalidOperationException("未发现海康相机"); + Console.WriteLine($"设备:{_selected.Name}"); + if (!await _camera.ConnectAsync(_selected)) throw new InvalidOperationException("连接失败"); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _camera.FrameArrived += frame => + { + if (!frame.Bgr.Empty() && frame.Bgr.Channels() == 3) ready.TrySetResult(); + }; + if (!await _pipeline.StartAsync()) throw new InvalidOperationException("启动失败"); + await ready.Task.WaitAsync(TimeSpan.FromSeconds(10)); + Console.WriteLine("PASS: 真实采集中直接调用 Application.Shutdown"); + } + // 不主动 Stop/Disconnect/Dispose,不依赖页面 Destroy。 + Shutdown(); + } + catch (Exception ex) + { + Console.Error.WriteLine(ex); + Shutdown(1); + } + } + + internal async Task VerifyAfterExitAsync() + { + try + { + if (!_exitObserved) throw new InvalidOperationException("未触发 WPF Exit"); + try + { + await _camera.StartAsync(); + throw new InvalidOperationException("退出后服务仍允许启动"); + } + catch (ObjectDisposedException) { } + _camera.Dispose(); + _pipeline.Dispose(); + Console.WriteLine("PASS: WPF 退出已释放服务,重复释放安全,退出后禁止重新启动"); + + if (_selected is not null) + { + // 原进程仍存活,证明是显式关闭设备,而非进程结束后的系统回收。 + using var reopened = new HikvisionCameraService(); + reopened.Error += Console.WriteLine; + if (!await reopened.ConnectAsync(_selected)) + throw new InvalidOperationException("退出清理后同一进程仍无法重新打开相机"); + Console.WriteLine("PASS: 原进程退出清理后立即重新打开同一海康相机"); + } + return 0; + } + catch (Exception ex) + { + Console.Error.WriteLine(ex); + return 1; + } + } +} diff --git a/tests/ShutdownSmoke/ShutdownSmoke.csproj b/tests/ShutdownSmoke/ShutdownSmoke.csproj new file mode 100644 index 0000000..480519f --- /dev/null +++ b/tests/ShutdownSmoke/ShutdownSmoke.csproj @@ -0,0 +1,13 @@ + + + Exe + net8.0-windows + true + enable + enable + x64 + + + + +