开发者

cache being modified instead of local variable (pass by ref)

开发者 https://www.devze.com 2023-03-08 07:57 出处:网络
I am writing a .net c# application. 开发者_JS百科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

I am writing a .net c# application.

开发者_JS百科

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?


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.


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)


Depending on the type the solution may simply be to clone the object/item on retrieval from the cache.

XmlNode Clone method

0

精彩评论

暂无评论...
验证码 换一张
取 消