Cache problem

  • Thread starter Thread starter Arjen
  • Start date Start date
A

Arjen

Hi,

I'm using the cache block of the enterprise lib Jan. 2006.

There is somethings strange going on.

I add a varable to the cache, let's say the string myData.
string myData = "1111111";
primitivesCache.Add("Key1", myData, CacheItemPriority.Normal, null, new
SlidingTime(TimeSpan.FromMinutes(15)));

When I do after this line this:
myData = "*****";

And I get my data out of the cache manager then myData has the value of
*********. I also tried to load it inside an other variable. Again the
value is the same.

How is it posible that the data in the cache is changed? Or not added
liked I did?

Thanks!
Arjen
 
Arjen said:
Hi,

I'm using the cache block of the enterprise lib Jan. 2006.

There is somethings strange going on.

I add a varable to the cache, let's say the string myData.
string myData = "1111111";
primitivesCache.Add("Key1", myData, CacheItemPriority.Normal, null, new
SlidingTime(TimeSpan.FromMinutes(15)));

When I do after this line this:
myData = "*****";

And I get my data out of the cache manager then myData has the value of
*********. I also tried to load it inside an other variable. Again the
value is the same.

How is it posible that the data in the cache is changed? Or not added
liked I did?

Please post a short but complete program that demonstrates your
problem. See Jon Skeet's page for a description of what constitutes a
"short but complete program":

http://www.yoda.arachsys.com/csharp/complete.html
 
Well, I found the problem... still strange...
I add an item to the cache.
After that I change the item, and also the item in the cache is changed
(why?).
Now I have made a copy of the variable after I add it to the cache.
This works fine.

Thanks.
Arjen
 
What type is the variable?

Is it a string, like the code in your original post? Or is it one of
your own classes? If it is an object of your own type (class) then I
know why....
 
Hi,

It's an arraylist with my own objects (classes).
So, it sounds like you know why...

Thanks,
Arjen
 
It's because what is cached is a _reference_ to the object instance.
Class instance are _reference types_, so your local variable and the
cache both store the same thing: a reference (or, if you prefer, a
pointer) to the same object in memory. Change the state (contents) of
the object, and it changes in both places because there is only one
object.

If you want to cache a copy of the object, not a reference to the same
object you're holding, then your class has to implement ICloneable and
you have to cache myObject.Clone(), not myObject.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top