C#C
C#9mo ago
yeon

Mixing `Volatile` with `Interlocked`

I believe this is safe to do so, but I'm asking this just in case.
private int refreshing = 0;

private void RefreshLobbies()
{
    // Skip if already refreshing
    if (Interlocked.CompareExchange(ref this.refreshing, 1, 0) != 0)
        return;

    /* Do some work here... */

    // Refreshing done, clear the flag
    Volatile.Write(ref this.refreshing, 0);
}

Can you mix Interlocked.CompareExchange with Volatile.Write like this?
I believe both would perform the atomic operations, so it should be safe to do so in this pattern.

Another question is whether the Interlocked.CompareExchange synchronizes-with Volatile.Write to create a happens-before relationship.
Which means, in C++ terms, if the Interlocked.CompareExchange returns 0, previous memory operations in /* Do some work here... */ should be also visible to the current thread.
Was this page helpful?