Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
297 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...