Why does MemoryCache throw NullReferenceException Why does MemoryCache throw NullReferenceException multithreading multithreading

Why does MemoryCache throw NullReferenceException


It would seem that Microsoft has fixed this, at least in .Net 4.5.2. Browsing referencesource.microsoft.com shows that there's now a lock around the access to the dictionary they're using to store internal data:

MemoryCacheEntry.cs

    internal void RemoveDependent(MemoryCacheEntryChangeMonitor dependent) {        lock (this) {            if (_fields._dependents != null) {                _fields._dependents.Remove(dependent);            }        }    }


I found this thread by NullReferenceExceptionin memory cache.My problem is receiving NullReferenceException when i was trying to add something to cache.

NullReferenceException   at System.Runtime.Caching.MemoryCacheStore.UpdateExpAndUsage(MemoryCacheEntry entry, Boolean updatePerfCounters)   at System.Runtime.Caching.MemoryCacheStore.AddOrGetExisting(MemoryCacheKey key, MemoryCacheEntry entry)   at System.Runtime.Caching.MemoryCache.AddOrGetExistingInternal(String key, Object value, CacheItemPolicy policy)   at System.Runtime.Caching.ObjectCache.Add(String key, Object value, CacheItemPolicy policy, String regionName)

MemoryCache is thread safe. We used one object in static field.Reason for NRE was one of other separate thread was trying to clear MemoryCache by calling cache.Dispose(); cache = new MemoryCache();problem is easy to reproduce in just 2 parallel tasks:one task will add new objectssecond one will call Dispose and new MemoryCache, just after 0.5 second you will receive NRE somewhere incide MemoryCache .net 4.6.1

i just replaced .Dispose and new MemoryCache with foreach(var kv in cache){ cache.remove(kv.key) }