-
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
Interlockedclass. -
public static T CompareExchange<T>(ref T a, T b, T c)) where T : classoverload can only be used with reference types (note thewhere T : classclause at the end). Instead of a boolean value, you can use theCompareExchange(Int32, Int32, Int32)overload, and switch the boolean with anInt32.Alternatively, if you want to keep your variables of boolean type, you can use the
lockmethod to ensure thread safety. This would be a slightly slower solution, but depending on your performance requirements, this might be still the preferred way.