using System; using System.Diagnostics; using System.Net.Http; using System.Threading; namespace FastGithub.ReverseProxy { /// /// 表示自主管理生命周期的的HttpMessageHandler /// [DebuggerDisplay("LifeTime = {lifeTime}")] sealed class LifetimeHttpHandler : DelegatingHandler { /// /// 生命周期 /// private readonly TimeSpan lifeTime; /// /// Token取消源 /// private readonly CancellationTokenSource tokenSource = new(); /// /// 具有生命周期的HttpHandler /// /// HttpHandler /// 拦截器的生命周期 /// 失效回调 /// public LifetimeHttpHandler(HttpMessageHandler handler, TimeSpan lifeTime, Action deactivateAction) : base(handler) { if (deactivateAction == null) { throw new ArgumentNullException(nameof(deactivateAction)); } this.lifeTime = lifeTime; this.tokenSource.Token.Register(() => { this.tokenSource.Dispose(); deactivateAction.Invoke(this); }, useSynchronizationContext: false); this.tokenSource.CancelAfter(lifeTime); } /// /// 这里不释放资源 /// /// protected override void Dispose(bool disposing) { } } }