“对易失性字段的引用不会被视为易失性” 影响
以下代码
using System.Threading;
class Test
{
volatile int counter = 0;
public void Increment()
{
Interlocked.Increment(ref counter);
}
}
引发以下编译器警告:
"A reference to a volatile field will not be treated as volatile"
我在这里做错了什么来引发此警告吗? 为什么编译器会对此发出警告?
The following code
using System.Threading;
class Test
{
volatile int counter = 0;
public void Increment()
{
Interlocked.Increment(ref counter);
}
}
Raises the following compiler warning:
"A reference to a volatile field will not be treated as volatile"
Am I doing something wrong here to raise this warning? Why does the compiler me warn about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你没有做错任何事。 根据文档:
You are not doing anything wrong. According to the documentation:
基本上警告是,当您通过引用传递易失性字段时,调用代码不知道以易失性方式处理它。 对于 Interlocked.Increment 来说,由于该方法的性质,这可能并不重要 - 但如果您使用 Interlocked,则无论如何您都不需要变量是易失性的。
一般来说,我认为我会避免混合两者 - 如果您使用 Interlocked,请在任何地方(使用
Interlocked.CompareExchange(ref counter, 0, 0)
来阅读它)。 我个人不能说我经常使用 volatile。 对于简单的计数器,我可能使用互锁,但对于大多数任务我更有可能使用锁。Basically the warning is that when you pass a volatile field by reference, the calling code doesn't know to treat it in a volatile manner. For Interlocked.Increment that probably doesn't matter, due to the nature of the method - but then you don't need the variable to be volatile anyway if you're using Interlocked.
In general, I think I'd avoid mixing the two - if you're using Interlocked, do it everywhere (using
Interlocked.CompareExchange(ref counter, 0, 0)
to read it). I can't say I use volatile very often, personally. For simple counters I might use Interlocked, but I'm more likely to use a lock for most tasks.用这个:
Use this:
您收到错误是因为您通过引用传递字段。 我认为这意味着目标方法不知道该字段被标记为易失性,因此不会将其视为易失性。
You're getting the error because you're passing the field by reference. I think what this means is that the target method has no idea the field is marked as
volatile
, and therefore will not treat it as such.