vb.net .NET DateTime 线程安全吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14345164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is .NET DateTime thread safe
提问by user632942
Is .NET DateTime thread safe? I'm not worried if the readoperation returns incorrect value, my only concern is: will DateTime object get corrupted if not synchronized.
.NET DateTime 线程安全吗?如果读取操作返回不正确的值,我并不担心,我唯一担心的是:如果不同步 DateTime 对象是否会损坏。
回答by CodesInChaos
Reads and writes to DateTimefields 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 DateTimemight contain values of different age when used from multiple threads at the same time.
本质上,DateTime当同时从多个线程使用时,a 的两个 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 Int64for the field, and work on it with atomic methods from Threadand Interlocked. Then use new DateTime(ticks)and dateTime.Ticksto convert to/from DateTime.
作为替代方案,您可以Int64对字段使用 ,并使用来自Thread和 的原子方法处理它Interlocked。然后使用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.
这种类型的所有成员都是线程安全的。看起来修改实例状态的成员实际上返回一个用新值初始化的新实例。与任何其他类型一样,读取和写入包含此类型实例的共享变量必须受锁保护以保证线程安全。
分配这种类型的实例在所有硬件平台上都不是线程安全的,因为该实例的二进制表示可能太大而无法在单个原子操作中分配。
回答by Oded
DateTimeis an immutable value type (struct). You cannot change an instance once created.
DateTime是一个不可变的值类型 (struct)。实例一经创建便无法更改。
It will not get corrupted and is thread safe.
它不会被破坏并且是线程安全的。
If you are changing a DateTimevariablefrom multiple threads (either writing or reading/writing), you need to synchronize - as this operation is notthread safe.
如果要从多个线程更改DateTime变量(写入或读取/写入),则需要同步 - 因为此操作不是线程安全的。

