fix: 应用退出时停止采集并按顺序释放相机和推理资源

This commit is contained in:
sophelper 2026-11-05 21:40:01 +08:00
parent d079c59b4f
commit 0cc83d0a71
7 changed files with 219 additions and 19 deletions

View File

@ -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`。

View File

@ -20,6 +20,9 @@ namespace SopHelper;
/// </summary>
public partial class App
{
private ICameraService? _camera;
private DetectionPipeline? _pipeline;
/// <summary>
/// 注册应用程序所需的类型和服务
/// </summary>
@ -47,8 +50,11 @@ public partial class App
// 引擎层三件套。它们在 SopHelper.Engine 程序集里,上面的 [Model] 反射扫描只覆盖本程序集,
// 所以必须显式注册,否则 SOP 页 ViewModel 的构造注入解析不出来。
_ = containerRegistry.RegisterSingleton<ICameraService, CameraService>();
_ = containerRegistry.RegisterSingleton<DetectionPipeline>();
// 共享硬件和推理由应用持有;页面销毁和容器回收不能代替应用退出清理。
_camera = new CameraService();
_pipeline = new DetectionPipeline(_camera);
containerRegistry.RegisterInstance<ICameraService>(_camera);
containerRegistry.RegisterInstance(_pipeline);
_ = containerRegistry.RegisterSingleton<SopEngine>();
// 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);
}
}
/// <summary>
/// 自动寻找ViewModel并绑定到View,要求ViewModel命名为View的全名加上ViewModel,比如MainWindow的ViewModel命名为MainWindowViewModel
/// </summary>

View File

@ -41,6 +41,7 @@ public class SopPageViewModel : ViewModelBase
private readonly object _frameLock = new();
private Mat? _pending;
private bool _destroyed;
/// <summary>最近一次处理过的帧(快照按钮存盘用,由推理线程写入)</summary>
private FrameResult? _lastFrame;
@ -297,10 +298,10 @@ public class SopPageViewModel : ViewModelBase
/// </summary>
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();
}

View File

@ -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<List<CameraInfo>> 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<bool> 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<bool> 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<bool> 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(); }
}
}

View File

@ -50,6 +50,7 @@ public class DetectionPipeline : IDisposable
private PipelineOptions _options = new();
private long _seen;
private long _processed;
private bool _disposed;
/// <summary>管线就绪度(缺哪个模型就在这里报告,界面据此提示)</summary>
public List<string> Warnings { get; private set; } = [];
@ -186,6 +187,8 @@ public class DetectionPipeline : IDisposable
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_camera.FrameArrived -= OnFrame;
_yolo.Dispose();
_hand.Dispose();

View File

@ -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();
}
}
/// <summary>不创建窗口;使用正式服务注册及 WPF Shutdown → App.OnExit 链路。</summary>
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<ICameraService>();
_pipeline = registry.Resolve<DetectionPipeline>();
_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<int> 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;
}
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj" />
</ItemGroup>
</Project>