在ASP.NET缓存模式 [英] Caching Patterns in ASP.NET
问题描述
所以我只是固定在一个框架,我正在开发一个错误。伪伪code是这样的:
So I just fixed a bug in a framework I'm developing. The pseudo-pseudocode looks like this:
myoldObject = new MyObject { someValue = "old value" };
cache.Insert("myObjectKey", myoldObject);
myNewObject = cache.Get("myObjectKey");
myNewObject.someValue = "new value";
if(myObject.someValue != cache.Get("myObjectKey").someValue)
myObject.SaveToDatabase();
所以,基本上,我是从缓存后的原始对象比较缓存的对象,以确定我需要将其保存到情况下,数据库它改变了得到一个对象,然后。这个问题的出现是因为原来的对象是一个参考...所以变化someValue中也改变了引用缓存的对象,所以它永远不会保存到数据库中。我通过克隆对象关闭的缓存版本,切断参考,让我来比较新的对象对缓存的1个固定的。
So, essentially, I was getting an object from the cache, and then later on comparing the original object to the cached object to see if I need to save it to the database in case it's changed. The problem arose because the original object is a reference...so changing someValue also changed the referenced cached object, so it'd never save back to the database. I fixed it by cloning the object off of the cached version, severing the reference and allowing me to compare the new object against the cached one.
我的问题是:有没有更好的办法做到这一点,一些模式,你可以推荐我不能是已做过的唯一的人?)
My question is: is there a better way to do this, some pattern, that you could recommend? I can't be the only person that's done this before :)
推荐答案
肮脏的跟踪处理这种正常的方式,我想。是这样的:
Dirty tracking is the normal way to handle this, I think. Something like:
class MyObject {
public string SomeValue {
get { return _someValue; }
set {
if (value != SomeValue) {
IsDirty = true;
_someValue = value;
}
}
public bool IsDirty {
get;
private set;
}
void SaveToDatabase() {
base.SaveToDatabase();
IsDirty = false;
}
}
myoldObject = new MyObject { someValue = "old value" };
cache.Insert("myObjectKey", myoldObject);
myNewObject = cache.Get("myObjectKey");
myNewObject.someValue = "new value";
if(myNewObject.IsDirty)
myNewObject.SaveToDatabase();
这篇关于在ASP.NET缓存模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!