I have two questions:
-
Is there a need to use Interlocked class for accessing boolean values? Isn’t a read or a write to a boolean value atomic by default?
-
I tried using Interlocked.CompareExchange on a boolean and got the following error:
bool value = true; Interlocked.CompareExchange<bool>(ref value, false, true);Error: The type ‘bool’ must be a reference type in order to use it as parameter ‘T’ in the generic type or method ‘System.Threading.Interlocked.CompareExchange(ref T, T, T)’
How do I go about solving this problem?
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.