Are reads and writes to properties atomic in C#?

前端 未结 6 1999
迷失自我
迷失自我 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:15

    If you examine the auto-generated code, you'll see that auto-generated properties are NOT thread safe - they are simple get/set to a generated field. In fact, it would be too much of a performance hit to do so (especially when not needed).

    In addition, if you are planning on access int/bool values from multiple threads then you should mark it (the field) as volatile. This basically prevents multithreading issues related to CPU registers. (This is in addition to locking, not an alternative)

提交回复
热议问题