Do I need to lock or mark as volatile when accessing a simple boolean flag in C#?

前端 未结 5 1599
余生分开走
余生分开走 2020-11-28 23:38

Lets just say you have a simple operation that runs on a background thread. You want to provide a way to cancel this operation so you create a boolean flag that you set to t

5条回答
  •  执念已碎
    2020-11-29 00:02

    _cancelled must be volatile. (if you don't choose to lock)

    If one thread changes the value of _cancelled, other threads might not see the updated result.

    Also, I think the read/write operations of _cancelled are atomic:

    Section 12.6.6 of the CLI spec states: "A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size."

提交回复
热议问题