Are primitive data types in c# atomic (thread safe)?

前端 未结 4 1687
野趣味
野趣味 2020-12-06 05:56

For example, do I need to lock a bool value when multithreading?

4条回答
  •  伪装坚强ぢ
    2020-12-06 06:50

    Sort of. There's an excellent thread about this here, but the short version is, while a given read or write may be atomic, that's almost never what you're doing. For example, if you want to increment an integer, you need to 1) read the value, 2) add one to the value and 3) store the value back. Any of those operations can be interrupted.

    That's the reason for classes such as "Interlocked".

提交回复
热议问题