diff --git a/.hgignore b/.hgignore index a962e75a4..e398d2c33 100644 --- a/.hgignore +++ b/.hgignore @@ -8,3 +8,4 @@ syntax: glob glob:Dapper.Contrib/NuGet.exe *.nupkg */NuGet.exe +_ReSharper.* diff --git a/Dapper/SqlMapper.cs b/Dapper/SqlMapper.cs index a38aabc53..888ed319f 100644 --- a/Dapper/SqlMapper.cs +++ b/Dapper/SqlMapper.cs @@ -135,8 +135,34 @@ private static void PurgeQueryCache(Identity key) static readonly System.Collections.Concurrent.ConcurrentDictionary _queryCache = new System.Collections.Concurrent.ConcurrentDictionary(); private static void SetQueryCache(Identity key, CacheInfo value) { + if(Interlocked.Increment(ref collect)==COLLECT_PER_ITEMS) + { + CollectCacheGarbage(); + } _queryCache[key] = value; } + + private static void CollectCacheGarbage() + { + try + { + foreach (var pair in _queryCache) + { + if (pair.Value.GetHitCount() <= COLLECT_HIT_COUNT_MIN) + { + CacheInfo cache; + _queryCache.TryRemove(pair.Key, out cache); + } + } + } + finally + { + Interlocked.Exchange(ref collect, 0); + } + } + + private const int COLLECT_PER_ITEMS = 1000, COLLECT_HIT_COUNT_MIN = 0; + private static int collect; private static bool TryGetQueryCache(Identity key, out CacheInfo value) { if(_queryCache.TryGetValue(key, out value))