Skip to content

Commit fae3641

Browse files
committed
更新LifetimeInterceptor
1 parent da44a65 commit fae3641

File tree

2 files changed

+23
-14
lines changed

2 files changed

+23
-14
lines changed

WebApiClient/Internal/HttpApiFactories/InterceptorCleaner.cs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,13 @@ public void Add(LifetimeInterceptor interceptor)
4747
/// </summary>
4848
private async void StartCleanup()
4949
{
50-
while (this.Cleanup() == false)
50+
do
5151
{
52-
await Task.Delay(this.CleanupInterval).ConfigureAwait(false);
52+
await Task
53+
.Delay(this.CleanupInterval)
54+
.ConfigureAwait(false);
5355
}
56+
while (this.Cleanup() == false);
5457
}
5558

5659
/// <summary>
@@ -67,17 +70,15 @@ private bool Cleanup()
6770
if (entry.CanDispose == false)
6871
{
6972
this.trackingEntries.Enqueue(entry);
73+
continue;
7074
}
71-
else
75+
76+
entry.Dispose();
77+
if (Interlocked.Decrement(ref this.trackingEntryCount) == 0)
7278
{
73-
entry.Dispose();
74-
if (Interlocked.Decrement(ref this.trackingEntryCount) == 0)
75-
{
76-
return true;
77-
}
79+
return true;
7880
}
7981
}
80-
8182
return false;
8283
}
8384

WebApiClient/Internal/HttpApiFactories/LifetimeInterceptor.cs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
using System;
2-
using System.Threading.Tasks;
2+
using System.Threading;
33
using WebApiClient.Defaults;
44

55
namespace WebApiClient
@@ -9,6 +9,11 @@ namespace WebApiClient
99
/// </summary>
1010
class LifetimeInterceptor : ApiInterceptor
1111
{
12+
/// <summary>
13+
/// Token取消源
14+
/// </summary>
15+
private readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
16+
1217
/// <summary>
1318
/// 具有生命周期的拦截器
1419
/// </summary>
@@ -24,10 +29,13 @@ public LifetimeInterceptor(HttpApiConfig httpApiConfig, TimeSpan lifeTime, Actio
2429
throw new ArgumentNullException(nameof(deactivateAction));
2530
}
2631

27-
Task.Delay(lifeTime)
28-
.ConfigureAwait(false)
29-
.GetAwaiter()
30-
.OnCompleted(() => deactivateAction(this));
32+
this.tokenSource.Token.Register(() =>
33+
{
34+
this.tokenSource.Dispose();
35+
deactivateAction.Invoke(this);
36+
}, useSynchronizationContext: false);
37+
38+
this.tokenSource.CancelAfter(lifeTime);
3139
}
3240

3341
/// <summary>

0 commit comments

Comments
 (0)