© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•10mo ago•
22 replies
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);
}
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
Interlocked.CompareExchange
with
Volatile.Write
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
Interlocked.CompareExchange
synchronizes-with
Volatile.Write
Volatile.Write
to create a happens-before relationship.
Which means, in C++ terms, if the
Interlocked.CompareExchange
Interlocked.CompareExchange
returns
0
0
, previous memory operations in
/* Do some work here... */
/* Do some work here... */
should be also visible to the current thread.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Race condition with Interlocked.Exchange
C#CC# / help
14mo ago
Threadsafety and Interlocked.CompareExchange
C#CC# / help
2y ago
Solution to mixing SQL queries with entity framework entities
C#CC# / help
4y ago
❔ Mixing EF Core and another SQL library
C#CC# / help
3y ago