DnscryptProxyHostedService.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Microsoft.Extensions.Hosting;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace FastGithub.ReverseProxy
  9. {
  10. /// <summary>
  11. /// DnscryptProxy后台服务
  12. /// </summary>
  13. sealed class DnscryptProxyHostedService : IHostedService
  14. {
  15. private const string dnscryptFile = "dnscrypt-proxy";
  16. private readonly ILogger<DnscryptProxyHostedService> logger;
  17. private Process? dnscryptProcess;
  18. /// <summary>
  19. /// DnscryptProxy后台服务
  20. /// </summary>
  21. /// <param name="logger"></param>
  22. public DnscryptProxyHostedService(ILogger<DnscryptProxyHostedService> logger)
  23. {
  24. this.logger = logger;
  25. }
  26. /// <summary>
  27. /// 启动dnscrypt-proxy
  28. /// </summary>
  29. /// <param name="cancellationToken"></param>
  30. /// <returns></returns>
  31. public Task StartAsync(CancellationToken cancellationToken)
  32. {
  33. try
  34. {
  35. var fileName = dnscryptFile;
  36. if (OperatingSystem.IsWindows())
  37. {
  38. fileName = $"{dnscryptFile}.exe";
  39. }
  40. if (File.Exists(fileName) == true)
  41. {
  42. this.dnscryptProcess = Process.Start(new ProcessStartInfo
  43. {
  44. FileName = fileName,
  45. UseShellExecute = true,
  46. CreateNoWindow = true,
  47. WindowStyle = ProcessWindowStyle.Hidden
  48. });
  49. };
  50. }
  51. catch (Exception ex)
  52. {
  53. this.logger.LogWarning(ex.Message);
  54. }
  55. return Task.CompletedTask;
  56. }
  57. /// <summary>
  58. /// 停止dnscrypt-proxy
  59. /// </summary>
  60. /// <param name="cancellationToken"></param>
  61. /// <returns></returns>
  62. public Task StopAsync(CancellationToken cancellationToken)
  63. {
  64. if (this.dnscryptProcess != null)
  65. {
  66. this.dnscryptProcess.Kill();
  67. }
  68. return Task.CompletedTask;
  69. }
  70. }
  71. }