缓存(或其他变量)可以在代码执行期间改变吗?

发布于 2024-10-19 16:48:41 字数 463 浏览 4 评论 0原文

这可能只是一个理论上的问题,但我一直无法找到令人满意的答案。

我在我的一个网站上使用缓存,这让我思考它的数据以及它何时以及是否发生变化。某些代码执行期间缓存会发生变化吗?

这是一个示例

if (Cache["name"] != null) {

    // Long and heavy code execution done here

    if (Cache["name"] == null) Response.Write("Lost the data");
}

更改缓存的过程可以与上述代码并行运行还是等待它完成?
理论上是否有可能打印“丢失数据”?

如果是,那么首先保存变量总是好的做法还是始终检查null并且从不非null

提前致谢!

/尼克拉斯

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

就像说晚安 2024-10-26 16:48:41

绝对可以。

始终从缓存中快照值,并使用快照:

var snapshot = Cache["name"];
if(snapshot != null) {...}

并在整个过程中使用snapshot。当谈到线程时,上述通常是一种明智的方法;唯一需要注意的是,您可能需要查看 Interlocked 中的一系列方法,这些方法可以让您(安全地)查看变量/字段是否在您未查看时发生更改,并且仅应用更改没有改变。

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.

空宴 2024-10-26 16:48:41

它肯定会过期,因此在使用它之前应该检查是否为空。正如你所说,保留一份保存的副本来处理是很好的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文