LifetimeHttpHandler.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using FastGithub.DomainResolve;
  2. using System;
  3. using System.Net.Http;
  4. using System.Threading;
  5. namespace FastGithub.Http
  6. {
  7. /// <summary>
  8. /// 表示自主管理生命周期的的HttpMessageHandler
  9. /// </summary>
  10. sealed class LifetimeHttpHandler : DelegatingHandler
  11. {
  12. private readonly Timer timer;
  13. public LifeTimeKey LifeTimeKey { get; }
  14. /// <summary>
  15. /// 具有生命周期的HttpHandler
  16. /// </summary>
  17. /// <param name="domainResolver"></param>
  18. /// <param name="lifeTimeKey"></param>
  19. /// <param name="lifeTime"></param>
  20. /// <param name="deactivateAction"></param>
  21. public LifetimeHttpHandler(IDomainResolver domainResolver, LifeTimeKey lifeTimeKey, TimeSpan lifeTime, Action<LifetimeHttpHandler> deactivateAction)
  22. {
  23. this.LifeTimeKey = lifeTimeKey;
  24. this.InnerHandler = new HttpClientHandler(lifeTimeKey.DomainConfig, domainResolver);
  25. this.timer = new Timer(this.OnTimerCallback, deactivateAction, lifeTime, Timeout.InfiniteTimeSpan);
  26. }
  27. /// <summary>
  28. /// timer触发时
  29. /// </summary>
  30. /// <param name="state"></param>
  31. private void OnTimerCallback(object? state)
  32. {
  33. this.timer.Dispose();
  34. ((Action<LifetimeHttpHandler>)(state!))(this);
  35. }
  36. /// <summary>
  37. /// 这里不释放资源
  38. /// </summary>
  39. /// <param name="disposing"></param>
  40. protected override void Dispose(bool disposing)
  41. {
  42. }
  43. }
  44. }