Are reads and writes to properties atomic in C#?

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

    Atomicity just means that if more than one thread is writing to a variable, its value won't get corrupted (e.g. if it takes up two bytes, you will never get thread one's high byte and thread two's low byte). It does not mean the variable is thread-safe. You can still get the usual threading problems of one thread not seeing anothers changes etc.

    For thread-safety you need to use locking (or volatile, but this is harder to reason about). There is nothing special about properties - they need to be made explicitly thread-safe too.

提交回复
热议问题