In .NET framework, atomic operation CompareAndExchange is only defined for int
, long
, double
and reference type. But I need CompareAndExchange for bool
type. How can I implement CompareAndSwap
for bool
?
Asked
Active
Viewed 282 times
5

user
- 5,335
- 7
- 47
- 63
2 Answers
6
You can define wrapper boolean values, and use the CompareExchange
overload for T where T : class
, like this:
private static object TrueObj = true;
private static object FalseObj = false;
...
object val = TrueObj;
object result = Interlocked.CompareExchange(ref val, TrueObj, FalseObj);
if (val == FalseObj) { // Alternatively you could use if (!(bool)val) ...
...
}

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
-
Nice. What I really like about your approach is that there is only a one-time boxing cost. – Steven Jun 30 '13 at 17:32
1
An alternative to dablinkenlight's approach would be to use the Int32
overload where 0
is false
and any non-zero value is true
.

keyboardP
- 68,824
- 13
- 156
- 205