Skip to content

Commit

Permalink
add implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
adamsitnik committed Aug 18, 2021
1 parent 40df3a3 commit 378bfbe
Showing 1 changed file with 16 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ public class MemoryCache : IMemoryCache
internal readonly ILogger _logger;

private readonly MemoryCacheOptions _options;
private readonly ConcurrentDictionary<object, CacheEntry> _entries;

private ConcurrentDictionary<object, CacheEntry> _entries;
private long _cacheSize;
private bool _disposed;
private DateTimeOffset _lastExpirationScan;
Expand Down Expand Up @@ -260,8 +260,8 @@ public bool TryGetValue(object key, out object result)
public void Remove(object key)
{
ValidateCacheKey(key);

CheckDisposed();

if (_entries.TryRemove(key, out CacheEntry entry))
{
if (_options.SizeLimit.HasValue)
Expand All @@ -281,7 +281,17 @@ public void Remove(object key)
/// </summary>
public void Clear()
{
CheckDisposed();

var oldEntries = Interlocked.Exchange(ref _entries, new ConcurrentDictionary<object, CacheEntry>());
Interlocked.Exchange(ref _cacheSize, 0);

foreach (var entry in oldEntries)
{
entry.Value.SetExpired(EvictionReason.Removed);
entry.Value.InvokeEvictionCallbacks();
}
oldEntries.Clear();
}

private void RemoveEntry(CacheEntry entry)
Expand Down Expand Up @@ -325,7 +335,8 @@ private static void ScanForExpiredItems(MemoryCache cache)
{
DateTimeOffset now = cache._lastExpirationScan = cache._options.Clock.UtcNow;

foreach (KeyValuePair<object, CacheEntry> item in cache._entries)
var entries = cache._entries; // Clear() can update the reference in the meantime
foreach (KeyValuePair<object, CacheEntry> item in entries)
{
CacheEntry entry = item.Value;

Expand Down Expand Up @@ -410,7 +421,8 @@ private void Compact(long removalSizeTarget, Func<CacheEntry, long> computeEntry

// Sort items by expired & priority status
DateTimeOffset now = _options.Clock.UtcNow;
foreach (KeyValuePair<object, CacheEntry> item in _entries)
var entries = _entries; // Clear() can update the reference in the meantime
foreach (KeyValuePair<object, CacheEntry> item in entries)
{
CacheEntry entry = item.Value;
if (entry.CheckExpired(now))
Expand Down

0 comments on commit 378bfbe

Please sign in to comment.