Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...