在InterLocked.CompareExchange之前读取值

时间:2018-04-05 17:37:42

标签: c# concurrency interlocked

我在InterLocked的C#用法中看到以下代码:

class MyObj {
// some class code .. 
int myVal
public void foo()
{
    int currVal = 0, newVal = 0;
    do
    {
        currVal = this.myVal;  // I have the question here ?
        newVal = this.newValue(currVal);
    } while (currVal != InterLocked.CompareExchange(ref this.myVal, newVal, currVal))
}
}

我知道InterLocked.CompareExchange会原子地运作。

但是,行:currVal = this.myVal会读取myVal的最新值吗?

我们不应该为此变量volatile或该行的currVal = InterLocked.Read(ref this.myVal)。 ?

0 个答案:

没有答案