Niklas
Niklas

Reputation: 13155

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

Upvotes: 5

Views: 73

Answers (2)

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

It can surely expire so checking for null should be done before using it. And as you said keeping a saved copy to work upon is good.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063814

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.

Upvotes: 4

Related Questions