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;
}
}
}