Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the cache (or other variables) change during code execution?

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

like image 894
Niklas Avatar asked Oct 12 '22 15:10

Niklas


1 Answers

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.

like image 64
Marc Gravell Avatar answered Oct 30 '22 02:10

Marc Gravell