Are reads and writes to properties atomic in C#?

前端 未结 6 1993
迷失自我
迷失自我 2020-12-14 17:32

Reads and writes to certain primitive types in C# such as bool and int are atomic.

(See section 5.5, \"5.5 Atomicity of variable reference

6条回答
  •  一生所求
    2020-12-14 18:29

    I'm a little unclear as to what you are asking here. It seems like you could be asking 1 of 2 questions

    1. Is the read of _foo while calling MyProperty atomic?
    2. Is the return value of MyProperty atomically set?

    For #1 the answer is yes. As the C# language spec (and CLI) states, the read and write of variables of certain specified types are guaranteed to be atomic. The type 'bool' is one of those types.

    As for #2 the best place to look is section 12.6.6 of the CLI spec. It states that

    A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size (the size of type native int) is atomic

    Considering to use the return value of MyProperty you must either be reading or writing the value, it's safe to assume it is set atomically.

提交回复
热议问题