简体   繁体   English

.NET DateTime线程是否安全

[英]Is .NET DateTime thread safe

Is .NET DateTime thread safe? .NET DateTime线程安全吗? I'm not worried if the read operation returns incorrect value, my only concern is: will DateTime object get corrupted if not synchronized. 我不担心读取操作是否返回不正确的值,我唯一担心的是:如果未同步,DateTime对象是否会被破坏。

Reads and writes to DateTime fields are not atomic (at least on 32 bit systems). DateTime字段的读取和写入不是原子的(至少在32位系统上)。

  • 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. 如果从一个线程读取并从另一个线程写入,则读取线程可能会损坏值。

  • Reading from multiple threads while having no writing threads at the same time is safe. 在没有写入线程的情况下从多个线程读取是安全的。

Essentially the two 32 bit halves of a DateTime might contain values of different age when used from multiple threads at the same time. 基本上,当从多个线程同时使用时, DateTime的两个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. 一次写入的高32位部分,另一次写入的低32位部分。

As an alternative you can use an Int64 for the field, and work on it with atomic methods from Thread and Interlocked . 作为替代方案,您可以将Int64用于该字段,并使用ThreadInterlocked原子方法对其进行处理。 Then use new DateTime(ticks) and dateTime.Ticks to convert to/from DateTime . 然后使用new DateTime(ticks)dateTime.Ticks转换为DateTime

MSDN says: MSDN说:

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 . 与任何其他类型一样, 必须通过锁保护对包含此类实例的共享变量的读写,以保证线程安全

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. 分配此类型的实例在所有硬件平台上都不是线程安全的,因为该实例的二进制表示可能太大而无法在单个原子操作中分配。

DateTime is an immutable value type (struct). DateTime是一个不可变的值类型(struct)。 You cannot change an instance once created. 创建后无法更改实例。

It will not get corrupted and is thread safe. 它不会被破坏并且是线程安全的。

If you are changing a DateTime variable from multiple threads (either writing or reading/writing), you need to synchronize - as this operation is not thread safe. 如果要从多个线程(写入或读取/写入)更改DateTime 变量 ,则需要同步 - 因为此操作不是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM