Is int? thread safe?(是整数吗?线程安全吗?)
问题描述
我知道在 .Net 中所有 32 位类型(例如,int
、bool
等)都是线程安全的.也就是说,不会有部分写入(根据规范).
I know that in .Net all 32-bit types (e.g, int
, bool
, etc) are thread safe. That is, there won't be a partial write (according to the specifications).
但是,同样适用于 int?
(可为空的 int)吗?
But, does the same apply for int?
(nullable int)?
推荐答案
这个问题措辞不佳,因此到目前为止的答案很混乱.问题应该是是否对 int 类型的变量进行读写?保证是 atomic?"
The question is poorly worded, and hence the confusion in the answers so far. The question should be "are reads and writes to a variable of type int? guaranteed to be atomic?"
不,绝对不是.规范在这一点上非常清楚:
No, absolutely not. The spec is extremely clear on this point:
以下数据类型的读写是原子的:bool、char、byte、sbyte、short、ushort、uint、int、float 和引用类型.此外,上一个列表中具有基础类型的枚举类型的读取和写入也是原子的.其他类型的读写,包括 long、ulong、double 和 decimal,以及用户定义的类型,不保证是原子的.
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.
线程完全有可能从可为空类型的共享内存变量中读取部分写入的值.
It is entirely possible for a thread to read a partially written value from a shared-memory variable of nullable type.
例如,假设你有一个 int?变量 x 目前的值为 null.因此,它包含一个设置为零的 int 和一个设置为 false 的 bool.现在在另一个线程上,您将可为空的 int "5" 写入 x.另一个线程从 x 读取不可为空的 int 零是完全合法的,因为 bool 中的true"可以在 5 设置为 int 之前设置.
For example, suppose you have an int? variable x which at present has the value null. It therefore contains an int, set to zero, and a bool, set to false. Now on another thread you write the nullable int "5" to x. It is perfectly legal for another thread to read the non-nullable int zero from x, because the "true" in the bool could be set before the 5 is set to the int.
这篇关于是整数吗?线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是整数吗?线程安全吗?
- 在 C# 中异步处理项目队列 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 使用 rss + c# 2022-01-01