Asp.Net缓存,修改从缓存中的对象,它改变缓存值 [英] Asp.Net Cache, modify an object from cache and it changes the cached value

查看:324
本文介绍了Asp.Net缓存,修改从缓存中的对象,它改变缓存值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Asp.Net缓存功能时,有一个问题。我的对象添加到高速缓存,然后在其他时间我从缓存对象,修改它的一个属性,然后将更改保存到数据库中。

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?

第1步:

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

第二步:

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

步骤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.

推荐答案

缓存正是如此,它缓存无论你把它付诸表决。

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

这篇关于Asp.Net缓存,修改从缓存中的对象,它改变缓存值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆