Skip to content

Commit

Permalink
Fixing concurrency issue in Memory Cache (#266)
Browse files Browse the repository at this point in the history
Using ConcurrentDictionary instead of HashSet for key map
  • Loading branch information
jkernsva authored and MichaCo committed Sep 25, 2019
1 parent 8c6b054 commit f2d6e11
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Caching.Memory;
Expand All @@ -24,21 +25,19 @@ public static bool Contains(this MemoryCache cache, object key)

internal static void RegisterChild(this MemoryCache cache, object parentKey, object childKey)
{
object temp;
if (cache.TryGetValue(parentKey, out temp))
if (cache.TryGetValue(parentKey, out var keys))
{
var set = (HashSet<object>)temp;
set.Add(childKey);
var keySet = (ConcurrentDictionary<object, bool>)keys;
keySet.TryAdd(childKey, true);
}
}

internal static void RemoveChilds(this MemoryCache cache, object region)
{
object keys;
if (cache.TryGetValue(region, out keys))
if (cache.TryGetValue(region, out var keys))
{
var keySet = (HashSet<object>)keys;
foreach (var key in keySet)
var keySet = (ConcurrentDictionary<object, bool>)keys;
foreach (var key in keySet.Keys)
{
cache.Remove(key);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using CacheManager.Core;
using CacheManager.Core.Internal;
using CacheManager.Core.Logging;
Expand Down Expand Up @@ -227,7 +227,7 @@ private void CreateRegionToken(string region)
SlidingExpiration = TimeSpan.MaxValue,
};

_cache.Set(region, new HashSet<object>(), options);
_cache.Set(region, new ConcurrentDictionary<object, bool>(), options);
}

private void ItemRemoved(object key, object value, EvictionReason reason, object state)
Expand Down

0 comments on commit f2d6e11

Please sign in to comment.