非阻塞变量更新

Non blocking variable updates

我将通过 Volatile.Write 实现对变量的非阻塞写入。我应该为这个变量的所有消费者使用 Volatile.Read 还是没有必要?如果我像往常一样读取这个变量(没有任何障碍),可能会产生什么样的影响?关于 Interlocked.Exchange

同样的问题

来自the documentation of the Volatile class

Calling one of these methods affects only a single memory access. To provide effective synchronization for a field, all access to the field must use Volatile.Read and Volatile.Write.

其中一个可能出错的地方是 reader 可能会将值读入寄存器一次,然后永远读取这个缓存的副本,而不会检查值是否已更改.

Interlocked.Exchange 相同。

通常,处理此类情况的最佳方法是将变量完全封装在 class 中,它提供 getter-setter 对,通过 VolatileInterlocked,从而保证永远不会通过任何其他方式访问该变量。