开发者

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 ch开发者_开发问答ange 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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜