Asp.Net Cache, modify an object from cache and it changes the cached value

前端 未结 1 358
猫巷女王i
猫巷女王i 2020-12-15 21:20

I\'m having an issue when using the Asp.Net Cache functionality. I add an object to the Cache then at another time I get that object from the Cache, modify one of it\'s pro

相关标签:
1条回答
  • 2020-12-15 21:42

    The cache does just that, it caches whatever you put into it.

    If you cache a reference type, retrieve the reference and modify it, of course the next time you retrieve the cached item it will reflect the modifications.

    If you wish to have an immutable cached item, use a struct.

    Cache.Insert("class", new MyClass() { Title = "original" }, null, 
        DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
    MyClass cachedClass = (MyClass)Cache.Get("class");
    cachedClass.Title = "new";
    
    MyClass cachedClass2 = (MyClass)Cache.Get("class");
    Debug.Assert(cachedClass2.Title == "new");
    
    Cache.Insert("struct", new MyStruct { Title = "original" }, null, 
        DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
    
    MyStruct cachedStruct = (MyStruct)Cache.Get("struct");
    cachedStruct.Title = "new";
    
    MyStruct cachedStruct2 = (MyStruct)Cache.Get("struct");
    Debug.Assert(cachedStruct2.Title != "new");
    
    0 讨论(0)
提交回复
热议问题