DnscryptProxyHostedService.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Microsoft.Extensions.Hosting;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace FastGithub.DomainResolve
  7. {
  8. /// <summary>
  9. /// DnscryptProxy后台服务
  10. /// </summary>
  11. sealed class DnscryptProxyHostedService : IHostedService
  12. {
  13. private readonly ILogger<DnscryptProxyHostedService> logger;
  14. private readonly DnscryptProxy dnscryptProxy;
  15. /// <summary>
  16. /// DnscryptProxy后台服务
  17. /// </summary>
  18. /// <param name="dnscryptProxy"></param>
  19. /// <param name="logger"></param>
  20. public DnscryptProxyHostedService(
  21. DnscryptProxy dnscryptProxy,
  22. ILogger<DnscryptProxyHostedService> logger)
  23. {
  24. this.dnscryptProxy = dnscryptProxy;
  25. this.logger = logger;
  26. }
  27. /// <summary>
  28. /// 启动dnscrypt-proxy
  29. /// </summary>
  30. /// <param name="cancellationToken"></param>
  31. /// <returns></returns>
  32. public async Task StartAsync(CancellationToken cancellationToken)
  33. {
  34. try
  35. {
  36. await this.dnscryptProxy.StartAsync(cancellationToken);
  37. this.logger.LogInformation($"{this.dnscryptProxy}启动成功");
  38. }
  39. catch (Exception ex)
  40. {
  41. this.logger.LogWarning($"{this.dnscryptProxy}启动失败:{ex.Message}");
  42. }
  43. }
  44. /// <summary>
  45. /// 停止dnscrypt-proxy
  46. /// </summary>
  47. /// <param name="cancellationToken"></param>
  48. /// <returns></returns>
  49. public Task StopAsync(CancellationToken cancellationToken)
  50. {
  51. try
  52. {
  53. this.dnscryptProxy.Stop();
  54. this.logger.LogInformation($"{this.dnscryptProxy}已停止");
  55. }
  56. catch (Exception ex)
  57. {
  58. this.logger.LogWarning($"{this.dnscryptProxy}停止失败:{ex.Message}");
  59. }
  60. return Task.CompletedTask;
  61. }
  62. }
  63. }