Skip to content
This repository has been archived by the owner on Sep 5, 2019. It is now read-only.

Commit

Permalink
Added tests for sliding expiration and improved TouchEntry (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
rstaib authored Jul 30, 2018
1 parent 4d31d6f commit a5f13ed
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 5 deletions.
43 changes: 43 additions & 0 deletions src/Core.Tests/TaskCacheTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>(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<string> 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<string, string>(cacheSize,
slidingExpiration);
var key = "Foo";

cache.TryAdd(key, Task.FromResult("Bar"));

// act
var exists = cache.TryGetValue(key, out Task<string> actual);

// assert
Assert.True(exists);
}

#endregion
}
}
12 changes: 7 additions & 5 deletions src/Core/TaskCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,17 @@ public bool TryGetValue(TKey key, out Task<TValue> 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()
Expand Down

0 comments on commit a5f13ed

Please sign in to comment.