【问题标题】:Asp.Net Cache, modify an object from cache and it changes the cached valueAsp.Net Cache,从缓存中修改对象并更改缓存值
【发布时间】:2011-02-17 02:18:56
【问题描述】:

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

但是,下次我从缓存中获取对象时,它包含更改的值。因此,当我修改对象时,它会修改缓存中包含的版本,即使我没有专门在缓存中更新它。有谁知道我如何从缓存中获取不引用缓存版本的对象?

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

第 3 步:

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

我意识到,通过上面的示例,对项目的任何更改都会反映在缓存中是有道理的,但我的情况有点复杂,我绝对不希望这种情况发生。

【问题讨论】:

  • 也许Itemstruct?一个完整的代码示例会很有帮助...

标签: asp.net caching


【解决方案1】:

缓存就是这样做的,它会缓存您放入其中的任何内容。

如果您缓存引用类型,则检索该引用并对其进行修改,当然下次您检索缓存项时它会反映修改。

如果您希望拥有一个不可变的缓存项,请使用结构。

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

【讨论】:

  • 我喜欢包含断言的回复!
猜你喜欢
  • 2017-05-09
  • 1970-01-01
  • 2023-02-25
  • 2016-04-15
  • 2018-09-05
  • 1970-01-01
  • 1970-01-01
  • 2011-02-28
  • 1970-01-01
相关资源
最近更新 更多