Search code examples
c#memorycache

C# MemoryCache Changing Data by Itself


Im working on MemoryCache here's several of my Code

Cache Class

    private static string policy = "__";
    public static void SaveTocache(string cacheKey, object savedItem,int hour = 43800)
    {
        if (!cacheKey.StartsWith(policy)) cacheKey = policy + cacheKey;
        CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
        cacheItemPolicy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(hour));
        RemoveFromCache(cacheKey);
        MemoryCache.Default.Add(cacheKey, savedItem, cacheItemPolicy);
    }
    public static T GetFromCache<T>(string cacheKey) where T : class
    {
        if (!cacheKey.StartsWith(policy)) cacheKey = policy + cacheKey;
        return MemoryCache.Default[cacheKey] as T;
    }
    public static void RemoveFromCache(string cacheKey)
    {
        if(!cacheKey.StartsWith(policy))cacheKey = policy + cacheKey;
        foreach (string key in MemoryCache.Default.Where(obj=> obj.Key.StartsWith(cacheKey)).Select(obj=> obj.Key))
        {
            MemoryCache.Default.Remove(key);
        }
    }
    public static bool IsInCache(string cacheKey)
    {
        if (!cacheKey.StartsWith(policy)) cacheKey = policy + cacheKey;
        return MemoryCache.Default[cacheKey] != null;
    }

So I Have a class called Log when I add a New Log theres a bug, heres the code

        Models.Log l = new Models.Log();
        l.LogId = Guid.NewGuid();
        l.Topic = topic;
        l.PIC = pic;
        l.LogStatusId = logStatus;
        l.LogRarityId = logRarity;
        l.LogTypeId = logType;
        l.SavedUser = savedUser;
        l.RequestedUser = requestedUser;
        l.Division = division;
        l.InsertedDate = DateTime.Now;
        l.Description = description;
        List<Models.Log> list = getData();
        Utility.Connect.Agla15Context.Logs.Add(l);
        Utility.Connect.Agla15Context.SaveChanges();
        string caches = cacheName;
        list.Add(l);
        Utility.CacheHelper.SaveTocache(caches, list);

The bug is myprevious object(cache values) for example: 3 Object A,B,C my next object(cache values) for example: 4 Object A,B,C,D

So I want to remove Object A,B,C by calling RemoveFromCache and adding Object(cache values) A,B,C,D

when I take take the cache by calling GetFromCache sometimes I got Object(cache values) A,B,C and sometimes I got Object(cache values) A,B,C,D what happen to my code.

Or the simplified one look like this

List<String> a = new List<String>(){"A","B","C"};
Utility.CacheHelper.SaveTocache("MyKey",a);
List<String> b = Utility.CacheHelper.GetFromCache<List<String>>("MyKey");//A,B,C
b.add("D");
Utility.CacheHelper.SaveTocache("MyKey",b);
for(int i=0;i<100;i++)
{
    List<String> b = Utility.CacheHelper.GetFromCache<List<String>>("MyKey");//Sometimes A,B,C sometimes A,B,C,D
}

Solution

  • Change:

    Utility.CacheHelper.SaveTocache("MyKey",a);
    

    to:

    Utility.CacheHelper.SaveTocache("MyKey",a.ToList());
    

    and:

    List<String> b = Utility.CacheHelper.GetFromCache<List<String>>("MyKey");
    

    to:

    List<String> b = Utility.CacheHelper.GetFromCache<List<String>>("MyKey").ToList();
    

    Technically just the latter change is required - the former will make it even more bulletproof.

    This is necessary since if any entries adding to the MemoryCache will be shared amongst callers - so if one caller manipulates the List then other callers will also see that manipulated list.

    By calling ToList you ensure that each caller gets its own copy of the List - so items added to one won't be seen in the other.