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.
This course topicThe standard . NET collection types are not thread safe, which can lead to a slew of problems, including race conditions, data corruption, and unexpected exceptions in modern multithreaded applications.
In common application models, only one thread at a time executes user code, which minimizes the need for thread safety. For this reason, the . NET class libraries are not thread safe by default.
This is thread-safe without any need for locking. Strings are reference types, so only a reference to the string is being modified. References are of a type are guaranteed to be atomic (Int32 on 32 bit systems and Int64 on 64 bit).
It tends to be between 0.5 and 15 milliseconds. As a result, repeated calls to the Now property in a short time interval, such as in a loop, may return the same value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With