Using Interlocked.CompareExchange() operation on a bool value?

You can use Interlocked.Exchange on an int for this:

using System.Threading;

// ...

int boolValue = 0; // Start False

// ...

if (Interlocked.Exchange(ref boolValue, 1) == 1) // Set to True
{
    // Was True
}
else
{
    // Was False                
}

  1. Reading or writing boolean values separately is atomic, but "compare and exchange" does both reading and writing to the same address, which means that entire transaction is not atomic. If multiple threads can write to this same location, you need to make the entire transaction atomic, by using the Interlocked class.

  2. public static T CompareExchange<T>(ref T a, T b, T c)) where T : class overload can only be used with reference types (note the where T : class clause at the end). Instead of a boolean value, you can use the CompareExchange(Int32, Int32, Int32) overload, and switch the boolean with an Int32.

    Alternatively, if you want to keep your variables of boolean type, you can use the lock method to ensure thread safety. This would be a slightly slower solution, but depending on your performance requirements, this might be still the preferred way.