diff --git a/PersistentQueue/Cache/Cache.cs b/PersistentQueue/Cache/Cache.cs index acc44b4..cbb8428 100644 --- a/PersistentQueue/Cache/Cache.cs +++ b/PersistentQueue/Cache/Cache.cs @@ -5,6 +5,7 @@ namespace Persistent.Queue.Cache; public class Cache : ICache where TKey : notnull { private readonly CancellationTokenSource _cts = new(); + private readonly CancellationToken _cancellationToken; private readonly Dictionary _items = new(); private readonly ReaderWriterLockSlim _lock = new(); private readonly TimeSpan _ttl; @@ -17,7 +18,8 @@ public Cache(TimeSpan ttl) else _ttl = TimeSpan.FromSeconds(1); - Task.Factory.StartNew(CleanupLoop, _cts.Token); + _cancellationToken = _cts.Token; + Task.Factory.StartNew(CleanupLoop, _cancellationToken); } public TValue GetOrCreate(TKey key, Func factory) @@ -142,10 +144,10 @@ private async void CleanupLoop() { try { - while (!_cts.IsCancellationRequested) + while (!_cancellationToken.IsCancellationRequested) { RemoveOldItems(); - await Task.Delay(_ttl / 2, _cts.Token); + await Task.Delay(_ttl / 2, _cancellationToken); } } catch (OperationCanceledException)