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.
Is .NET DateTime thread safe? I’m not worried if the read operation returns incorrect
Share
Reads and writes to
DateTimefields 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.
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.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.
As an alternative you can use an
Int64for the field, and work on it with atomic methods fromThreadandInterlocked. Then usenew DateTime(ticks)anddateTime.Ticksto convert to/fromDateTime.MSDN says: