是BOOL读/写的原子在C# [英] Is a bool read/write atomic in C#
本文介绍了是BOOL读/写的原子在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正在访问的布尔字段中的原子在C#中?特别是,我需要把一个锁周围的:
类Foo
{
私人布尔_bar;
// ...在任何线程(或多个线程)的一些功能
_bar = TRUE;
// ...相同的读
如果(_bar){...}
}
解决方案
是
读取及以下数据类型的读写是原子:布尔,字符,字节,为sbyte,总之,USHORT,UINT,整型,浮点和引用类型。
在 C#语言规格的发现。
编辑:这可能也是值得理解的<一个href="http://msdn.microsoft.com/en-us/library/x13ttww7%28VS.71%29.aspx">volatile关键字。
Is accessing a bool field atomic in C#? In particular, do I need to put a lock around:
class Foo
{
private bool _bar;
//... in some function on any thread (or many threads)
_bar = true;
//... same for a read
if (_bar) { ... }
}
解决方案
Yes.
Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.
as found in C# Language Spec.
Edit: It's probably also worthwhile understanding the volatile keyword.
这篇关于是BOOL读/写的原子在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文