From e9fe742c1581ebe64131912c2429ae0eb5bb4f6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=9B=BD=E4=BC=9F?= <366193849@qq.com> Date: Thu, 22 Jul 2021 13:41:40 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9dnscryptProxy=E7=9B=91?= =?UTF-8?q?=E6=8E=A7=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DnscryptProxyHostedService.cs | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/FastGithub.Dns.DnscryptProxy/DnscryptProxyHostedService.cs b/FastGithub.Dns.DnscryptProxy/DnscryptProxyHostedService.cs index 9890585..6f48234 100644 --- a/FastGithub.Dns.DnscryptProxy/DnscryptProxyHostedService.cs +++ b/FastGithub.Dns.DnscryptProxy/DnscryptProxyHostedService.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.Logging; using System; using System.Diagnostics; +using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -12,6 +13,7 @@ namespace FastGithub.Dns.DnscryptProxy /// sealed class DnscryptProxyHostedService : BackgroundService { + private bool isStopped = false; private const string dnscryptProxyFile = "dnscrypt-proxy"; private readonly ILogger logger; @@ -52,6 +54,26 @@ namespace FastGithub.Dns.DnscryptProxy return base.StartAsync(cancellationToken); } + /// + /// 后台监控 + /// + /// + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await Task.Yield(); + + var process = Process.GetProcessesByName(dnscryptProxyFile).FirstOrDefault(); + if (process != null) + { + process.WaitForExit(); + } + if (this.isStopped == false) + { + this.logger.LogCritical($"{dnscryptProxyFile}已停止运行,{nameof(FastGithub)}将无法解析域名。你可以把配置文件的PureDns修改为其它可用的DNS以临时使用。"); + } + } + /// /// 停止dnscrypt-proxy /// @@ -61,6 +83,7 @@ namespace FastGithub.Dns.DnscryptProxy { try { + this.isStopped = true; if (OperatingSystem.IsWindows()) { StartDnscryptProxy("-service stop", waitForExit: true); @@ -80,24 +103,6 @@ namespace FastGithub.Dns.DnscryptProxy return base.StopAsync(cancellationToken); } - /// - /// 后台任务 - /// - /// - /// - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - while (stoppingToken.IsCancellationRequested == false) - { - await Task.Delay(TimeSpan.FromSeconds(10d), stoppingToken); - var processes = Process.GetProcessesByName(dnscryptProxyFile); - if (processes.Length == 0) - { - this.logger.LogError($"检测到{dnscryptProxyFile}已停止运行,{nameof(FastGithub)}将无法使用。你可以把配置文件的PureDns修改为其它可用的DNS以临时使用。"); - } - } - } - /// /// 启动DnscryptProxy进程 ///