From a5f13ed2685f5916dc858dcf4c101e853d9d395d Mon Sep 17 00:00:00 2001 From: Rafael Staib Date: Mon, 30 Jul 2018 15:58:38 +0200 Subject: [PATCH] Added tests for sliding expiration and improved TouchEntry (#21) --- src/Core.Tests/TaskCacheTests.cs | 43 ++++++++++++++++++++++++++++++++ src/Core/TaskCache.cs | 12 +++++---- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/src/Core.Tests/TaskCacheTests.cs b/src/Core.Tests/TaskCacheTests.cs index a806ac4..f2ed5ab 100644 --- a/src/Core.Tests/TaskCacheTests.cs +++ b/src/Core.Tests/TaskCacheTests.cs @@ -390,5 +390,48 @@ public async Task TryGetValueResult() } #endregion + + #region Expiration + + [Fact(DisplayName = "VerifyExpirationFalse: Should return false if expired")] + public async Task VerifyExpirationFalse() + { + // arrange + var cacheSize = 10; + TimeSpan slidingExpiration = TimeSpan.FromMilliseconds(200); + var cache = new TaskCache(cacheSize, + slidingExpiration); + var key = "Foo"; + + cache.TryAdd(key, Task.FromResult("Bar")); + await Task.Delay(300).ConfigureAwait(false); + + // act + var exists = cache.TryGetValue(key, out Task actual); + + // assert + Assert.False(exists); + } + + [Fact(DisplayName = "VerifyExpirationTrue: Should return true if not expired")] + public void VerifyExpirationTrue() + { + // arrange + var cacheSize = 10; + TimeSpan slidingExpiration = TimeSpan.FromMilliseconds(500); + var cache = new TaskCache(cacheSize, + slidingExpiration); + var key = "Foo"; + + cache.TryAdd(key, Task.FromResult("Bar")); + + // act + var exists = cache.TryGetValue(key, out Task actual); + + // assert + Assert.True(exists); + } + + #endregion } } diff --git a/src/Core/TaskCache.cs b/src/Core/TaskCache.cs index 861f63a..a74f48e 100644 --- a/src/Core/TaskCache.cs +++ b/src/Core/TaskCache.cs @@ -113,15 +113,17 @@ public bool TryGetValue(TKey key, out Task value) private void TouchEntry(CacheEntry entry) { - _sync.Lock( - () => _first != entry.Rank, - () => + lock (_sync) + { + entry.LastTouched = DateTimeOffset.UtcNow; + + if (_first != entry.Rank) { - entry.LastTouched = DateTimeOffset.UtcNow; _ranking.Remove(entry.Rank); _ranking.AddFirst(entry.Rank); _first = entry.Rank; - }); + } + } } private void ClearSpaceForNewEntry()