This might just be a theoretical question but I haven't been able to find a satisfying answer to it.
I'm using the cache on one of my sites which got me thinking about it's data and when and if it changes. Can the cache change during the execution of some code?
Here's an example
if (Cache["name"] != null) {
// Long and heavy code execution done here
if (Cache["name"] == null) Response.Write("Lost the data");
}
Can the process that change the cache run parallel with the above code or does it wait until it has finished?
Is there a theoretical chance that this would print "Lost the data"?
If yes, is it always good practice to save the variable first or always check for null and never not null?
Thanks in advance!
/Niklas
Absolutely it can.
Always snapshot values from cache, and work with the snapshot:
var snapshot = Cache["name"];
if(snapshot != null) {...}
and use snapshot
throughout. When it comes to threading, the above is generally a sane approach; the only caveat being you might want to look at Interlocked
for a range of methods that let you see (safely) whether a variable/field changed while you weren't looking, and only apply a change it it hadn't changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With