简体   繁体   中英

Is .NET DateTime thread safe

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.

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.

  • 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.

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 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 says:

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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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