packServer/desktop/Services/Agent/AgentWindowsService.cs

55 lines
1.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// Windows 服务壳:SCM 拉起后在这里跑 <see cref="AgentHost"/>。
///
/// 进程仍是同一个 exe(<c>YuncangTrace.LocalService.exe --service</c>),
/// 但**不创建任何 WPF 窗口/托盘/HTTP 服务** —— Session 0 里没有桌面。
/// </summary>
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;
}
}
/// <summary>系统关机:与 Stop 一样尽力停下来(把扫码记录落盘)</summary>
protected override void OnShutdown() => OnStop();
}