Asp.Net缓存,修改缓存中的对象会改变缓存值

17

我在使用Asp.Net Cache功能时遇到了问题。我向Cache添加一个对象,然后在另一个时间从Cache获取该对象,修改其中一个属性,然后将更改保存到数据库中。

但是,下一次从Cache获取对象时,它包含已更改的值。因此,当我修改该对象时,它会修改Cache中包含的版本,即使我没有明确地在Cache中更新它。有人知道如何从Cache中获取不引用缓存版本的对象吗?

例如:

步骤1:

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

步骤2:

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

第三步:

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

我意识到以上示例中更改项会在缓存中反映出来是有意义的,但我的情况比较复杂,我绝对不希望发生这种情况。


也许 Item 是一个 struct 结构体?提供一个完整的代码示例会更有帮助... - Ron Klein
1个回答

17

缓存的作用就是缓存您放入其中的任何内容。

如果您缓存引用类型,检索引用并进行修改,那么当您下次检索缓存的项目时,它将反映修改。

如果您希望具有不可变缓存项,请使用结构体。

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

我喜欢包含断言的回复! - Bartosz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接