是.NET DateTime的线程安全线程、安全、NET、DateTime

2023-09-04 13:30:35 作者:爱情这场戏〃我没演技

是.NET DateTime的线程安全吗?我不担心,如果的读的操作返回不正确的值,我唯一关心的是:将DateTime对象遭到损坏,如果不同步

Is .NET DateTime thread safe? I'm not worried if the read operation returns incorrect value, my only concern is: will DateTime object get corrupted if not synchronized.

推荐答案

读取和写入的DateTime 字段是不是原子(至少在32位系统)。

Reads and writes to DateTime fields are not atomic (at least on 32 bit systems).

如果您从多个线程分配给同一属性的同时,你可能会破坏它。

If you assign from multiple threads to the same property at the same time you can corrupt it.

如果你从一个线程读取,并从另一个写,读线程可能会损坏值。

If you read from one thread, and write from another, the reading thread might get corrupted values.

阅读是安全的。

基本上,两个32位的半一的DateTime 可能包含不同年龄段的值从多个线程同时使用的时候。

Essentially the two 32 bit halves of a DateTime might contain values of different age when used from multiple threads at the same time.

您可以得到两个写的混合。高32位的组成部分之一写入,和另一个写低32位的部分。

You can get a mix of two writes. The high 32 bit part of one write, and the low 32 bit part of another write.

您也可以使用一个替代的的Int64 的领域,它的工作与原子的方法从互锁。然后使用新的日期时间(节拍) dateTime.Ticks 转换到/从日期时间

As an alternative you can use an Int64 for the field, and work on it with atomic methods from Thread and Interlocked. Then use new DateTime(ticks) and dateTime.Ticks to convert to/from DateTime.

MSDN说:

这类型的所有成员都是线程安全的。出现实际修改实例状态的成员返回新值初始化一个新的实例。与任何其他类型的读取和写入包含此类型的实例必须用锁进行保护,以保证线程安全的共享变量

如何在 .NET Framework 中实现一个线程安全的 System.Random 对象

All members of this type are thread safe. Members that appear to modify instance state actually return a new instance initialized with the new value. As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

指定此类型的一个实例不是线程安全的所有硬件平台上,因为该实例的二进制再presentation可能过大,在单个原子操作分配。

Assigning an instance of this type is not thread safe on all hardware platforms because the binary representation of that instance might be too large to assign in a single atomic operation.