我正在尝试在多线程.NET应用程序中的共享变量中设置位标志,但无法找到与托管的Interlocked类中的本机InterlockedOr函数的并行.我已经提出了以下用于执行| =赋值的代码,但无限循环的理论可能性让我感到不舒服:
long currentValue;
long updatedValue;
do
{
// Spin until successful update. Value must be read using Interlocked.Read()
// to be truly atomic on 32 bit systems (see MSDN).
currentFlags = Interlocked.Read(ref _currentFlags);
updatedValue = currentFlags | flag;
} while (currentFlags != Interlocked.CompareExchange(ref _currentFlags, updatedValue, currentFlags));
Run Code Online (Sandbox Code Playgroud)
是否可以仅使用Interlocked类中内置的函数以更安全的方式实现?如果可能的话,我想避免涉及显式锁定的解决方案.