在C#中访问bool场原子吗?特别是,我是否需要在周围放置锁:
class Foo
{
private bool _bar;
//... in some function on any thread (or many threads)
_bar = true;
//... same for a read
if (_bar) { ... }
}
在C#中访问bool场原子吗?特别是,我是否需要在周围放置锁:
class Foo
{
private bool _bar;
//... in some function on any thread (or many threads)
_bar = true;
//... same for a read
if (_bar) { ... }
}
Yes.
以下数据类型的读写是原子的:bool、char、byte、sbyte、short、ushort、uint、int、float和引用类型.
就像在C# Language Spec年发现的那样.
编辑:理解volatile关键字可能也是值得的.