XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.ServiceProcess;
using XFEToolBox.Client.Core.Search.Service;

namespace XFEToolBox.Indexing.Service.Host;

internal sealed class IndexingWindowsService : ServiceBase
{
    private readonly CancellationTokenSource lifetime = new();
    private Task? runner;

    public IndexingWindowsService()
    {
        ServiceName = IndexingServiceProtocol.ServiceName;
        CanStop = true;
        CanShutdown = true;
        AutoLog = false;
    }

    protected override void OnStart(string[] args) => runner = Task.Run(async () =>
    {
        try
        {
            await using var host = new IndexingServiceHost(DataDirectory);
            await host.RunAsync(lifetime.Token).ConfigureAwait(false);
        }
        catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
        catch (Exception error)
        {
            // SCM recovery can restart on failure; do not continue as a silently
            // running service with no trusted pipe endpoint.
            System.Diagnostics.Trace.TraceError("Indexing service stopped: {0}", error.GetType().Name);
            ExitCode = 1;
            ThreadPool.QueueUserWorkItem(_ => Stop());
        }
    });

    internal static string DataDirectory => Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "XFEToolBox", "IndexingService");

    protected override void OnStop()
    {
        lifetime.Cancel();
        RequestAdditionalTime(30_000);
        // Do not wait on the same runner when a fatal startup failure invokes Stop.
        if (runner is not null && Task.CurrentId != runner.Id)
            try { runner.Wait(TimeSpan.FromSeconds(25)); } catch (AggregateException) { }
    }

    protected override void OnShutdown() => OnStop();
}