编程语言
首页 > 编程语言> > c# – 可以为空的boolean(bool?)被认为是线程安全的吗?

c# – 可以为空的boolean(bool?)被认为是线程安全的吗?

作者:互联网

正如标题所说,在可读/写操作中被认为是可以为空的布尔(bool?)?我通过C#文档搜索无济于事.我知道只有某些原始类型在执行读/写操作时保证原子性,而Bool是这些类型中的一种.当然,可空的布尔是一个不同的故事;毕竟他们是对象所以我会说不,但……有人可以对这个问题有所了解吗?

解决方法:

C#不保证可空变量的读写是原子的.保证操作为原子的类型在规范的5.5节中定义(变量引用的原子性):

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic. Aside from the library functions designed for that purpose, there is no guarantee of atomic read-modify-write, such as in the case of increment or decrement.

请注意,虽然nullables可以为null,但它们不是引用类型.它们是具有运行时提供的特殊装箱行为的值类型.在规范的上下文中,如果需要特殊处理,它们被称为可空值类型.

标签:c,thread-safety,nullable,atomicity
来源: https://codeday.me/bug/20190516/1116605.html