22 December 2014

How in-memory cache can get inadvertently affected

Recently I was doing a code review for one my team mate and found an issue. The in memory cache items were getting inadvertently affected.

Let's see what was the issue by looking into the below sample cache creation and retrieval code.

Building the object need to be cached

public class GeneralData {
        public string Id { get; set; }
        public string Text {get;set;}
        // ...some other properties
    }
Dictionary<string, GeneralData> staticData = 
         new Dictionary<string, GeneralData>();
 staticData.Add("1"new GeneralData());
 staticData.Add("2"new GeneralData());
 staticData.Add("3"new GeneralData());

System.Runtime.Caching.MemoryCache cache = 
                          MemoryCache.Default;

Add item to be object into cache and set the cache expiration policy

cache.Add("CacheKey", staticData, 
      new DateTimeOffset(DateTime.Now.AddHours(2)));

Retrieve the cache item and perform processing

Dictionary<string, GeneralData> staticDataObject = 
              Dictionary<string, GeneralData>)
              MemoryCache.Default.Get("CacheKey");

// As part of some processing logic
// the staticDataObject was modified
staticDataObject.Remove("3");

In the above C# code sample at line 3, the GeneralData instance was removed from the local instance holding the reference to the in-memory cache object. This means the object is also removed from Cache object as well.

So pay extra attention while working with objects holding the reference to the in-memory objects, otherwise such problems will lead to inconsistent software application behavior.

No comments:

Post a Comment