Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

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

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 properties then save the changes to the database.

But, the next time I get the object from Cache it contains the changed values. So, when I modify the object it modifies the version which is contained in cache even though I haven't updated it in the Cache specifically. Does anyone know how I can get an object from the Cache which doesn't reference the cached version?

i.e.

Step 1:

Item item = new Item();
item.Title = "Test";
Cache.Insert("Test", item, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);

Step 2:

Item item = (Item)Cache.Get("test");
item.Title = "Test 1";

Step 3:

Item item = (Item)Cache.Get("test");
if(item.Title == "Test 1"){
    Response.Write("Object has been changed in the Cache.");
}

I realise that with the above example it would make sense that any changes to the item get reflected in cache but my situation is a bit more complicated and I definitely don't want this to happen.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...