缓存被修改而不是局部变量(通过引用传递)
我正在编写一个 .net C# 应用程序。
我从 xml 文件中检索一些数据,将数据缓存到 .net 缓存中,然后从我的方法中返回它。我对数据进行一些处理并将其返回到我的应用程序的另一部分。
下一次调用,我从缓存中读取,处理它并返回它等。
我遇到的问题是,对缓存数据执行的处理似乎修改了缓存而不是局部变量,这意味着下次我从缓存中读取时,它是返回的先前处理的已处理数据。
所以看起来从cache返回的数据是通过ref返回的,而不是value。
知道如何防止缓存被修改吗?
I am writing a .net c# application.
I retrieve some data from an xml file, cache the data to the .net cache and return it from my method. I perform some processing on the data and return it another part of my application.
Next call, I read from cache, process it and return it etc.
The problem I have is that the processing performed on the cache data seems to modify the cache and not the local variable which means the next time I read from cache, its the processed data from the previous processing that is returned.
So it seems that the data returned from cache is returned by ref and not value.
Any idea how I can prevent the cache being modified?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
内存缓存将存储指向该对象的指针。它就像一个全局变量。对缓存项的任何其他变量分配都将引用同一对象。这对于进程外或分布式缓存来说是不同的。对于这些类型的缓存,必须从缓存中序列化和反序列化对象。在这些情况下,您将获得副本。
如果您想模拟进程外的行为,您可以复制/克隆对象或在缓存外序列化/反序列化对象。
An in memory cache will store a pointer to the object. Its like a global variable. Any other variable assignments to the cached item will be referencing the same object. This is different for an out-of-process or distributed cache. For those types of cache, the object must be serialized and deserialized from the cache. In those cases you are getting copies.
If you want to simulate out-of-process that behavior you could copy/clone an object or serialize/deserialize the object in an out of the cache.
这是您需要了解的关于数据类型的相当基本的事情。
听起来你的缓存正在存储引用类型,即对象的实例或类似的东西。当您传递其中之一时,您会返回对该实例的引用,该引用本身实际上是按值传回的,也就是说您无法更改该引用,但当然它所引用的 thihg 可以更改,这就是您所看到的行为。
如果您希望此操作能够在您使用实例时保持不变,请先复制它们。 (如果是复杂类型,可能需要写一个clone方法)
This is a fairly fundamental thing that you will need to understand about datatypes.
It sounds like your cache is storing reference types i.e. instances of objects or something like that. When you are passed one of these you get back a reference to the instance, the reference itself is actually passed back by value, that is you can't change the reference, but of course the thihg that it is referring to can be changed, that is the behaviour you are seeing.
if you want this to work so that the instances are unchanged when you work with them, then make a copy of them first. (you may need to write a clone method if they are complex types)
根据类型,解决方案可能只是在从缓存检索时克隆对象/项目。
XmlNode 克隆方法
Depending on the type the solution may simply be to clone the object/item on retrieval from the cache.
XmlNode Clone method