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

Viewed 23883

I have two questions:

  1. 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?

  2. 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?

4 Answers
Related