Are C# structs thread safe?

前端 未结 6 2020
感情败类
感情败类 2020-12-03 12:22

Is a C# struct thread-safe?

For example if there is a:

struct Data
{
    int _number;
    public int Number { get { return _number; } set { _number =         


        
6条回答
  •  情深已故
    2020-12-03 13:03

    Different threads' direct reads and writes of different members of a mutable struct will not interfere with each other. Different threads' access to the same member via Interlocked methods will behave according to the semantics of those methods. These facts may allow mutable structs to allow thread-safe behavior.

    Mutable storage locations holding structs that offer no means of mutation except outright replacement offer no thread-safety whatsoever, except that in cases where a struct holds either a single 32-bit integer or a single object reference, an attempt to read a such a (single-item) struct storage location at the same time as it is being written is guaranteed to read entirely old data or entirely new data. Note that it is not possible to use any of the Interlocked methods with immutable structs--even structs which contain only a single integer or object reference.

提交回复
热议问题