using System; using System.ServiceProcess; using System.Threading; using System.Threading.Tasks; namespace YuncangTrace.LocalService.Services; /// /// Windows 服务壳:SCM 拉起后在这里跑 。 /// /// 进程仍是同一个 exe(YuncangTrace.LocalService.exe --service), /// 但**不创建任何 WPF 窗口/托盘/HTTP 服务** —— Session 0 里没有桌面。 /// public sealed class AgentWindowsService : ServiceBase { private CancellationTokenSource? _cts; private Task? _task; public AgentWindowsService() { ServiceName = ServiceInstaller.ServiceName; CanStop = true; CanShutdown = true; AutoLog = false; // 不写事件日志:没注册 EventLog source 会直接抛 } protected override void OnStart(string[] args) { _cts = new CancellationTokenSource(); _task = Task.Run(() => AgentHost.RunAsync(_cts.Token)); } protected override void OnStop() { try { _cts?.Cancel(); _task?.Wait(TimeSpan.FromSeconds(10)); } catch { // 停服务不能卡住 SCM } finally { _cts?.Dispose(); _cts = null; _task = null; } } /// 系统关机:与 Stop 一样尽力停下来(把扫码记录落盘) protected override void OnShutdown() => OnStop(); }