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
}
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.public static T CompareExchange<T>(ref T a, T b, T c)) where T : class
overload can only be used with reference types (note thewhere T : class
clause 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
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.