A
A
Amikko2013-04-17 19:25:03
.NET
Amikko, 2013-04-17 19:25:03

Missing entries from MemoryCache?

Uses System.Runtime.Caching.MemoryCache as key-value storage. An object can be saved twice (the second time is for updating the data). Moreover, the value of the ImportantInfo field in the saved object is not passed the second time, and it has to be taken from the old entry from the cache.

public static void Save(Entity entity)
    {
      var cache = MemoryCache.Default;
      var idKey = entity.Id.ToString();

      if (cache.Contains(idKey))
      {
        var message = string.Format(
          "In the cache already has a record with identifier {0}. Existing record will be replaced. ImportantInfo will be extracted from old entity record.",
          idKey);
        log.Info(message);
        entity.ImportantInfo = (cache.Get(idKey) as Entity).ImportantInfo;
      }

      var policy = new CacheItemPolicy
      {
        SlidingExpiration = Options.MemoryCachingTime	//30 минут.
      };

      cache.Set(idKey, entity, policy);
    }

<system.runtime.caching>
    <memoryCache>
      <namedCaches>
        <add name="default"
             cacheMemoryLimitMegabytes="0"
             physicalMemoryLimitPercentage="0"
             pollingInterval="00:02:00" />
      </namedCaches>
    </memoryCache>
  </system.runtime.caching>

With two consecutive calls (in time - 10 minutes between calls, no more) Save() for an object with the same ID, the entry “In the cache already has a record… Existing record will be replaced” is expected to appear in the log. However, sometimes it appears and sometimes it doesn't.
How can this be? It was expected that the record would be guaranteed to lie in the cache for half an hour (as SlidingExpiration was set), but it turns out that the records disappear from the cache?
There are about hundreds of objects in the cache. 300+. It seems not very much, but perhaps the cache is trying to optimize something and willfully overwrite the records? If so, can he be banned from doing it?
The docs on MSDN are sparse.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question