title: Difference between Interlocked.Exchange and Volatile.Write?
body: <p>What is the difference between <code>Interlocked.Exchange</code> and <code>Volatile.Write</code>?</p>
  <p>Both methods update value of some variable. Can someone summarize when to use each of them?</p>
  <ul>
  <li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked.exchange" rel="nofollow noreferrer"><code>Interlocked.Exchange</code></a></li>
  <li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.volatile.write" rel="nofollow noreferrer"><code>Volatile.Write</code></a></li>
  </ul>
  <p>In particular I need to update <code>double</code> item of my array, and I want another thread to see the freshest value. What is preferred? <code>Interlocked.Exchange(ref arr[3], myValue)</code> or <code>Volatile.Write(ref arr[3], info);</code> where <code>arr</code> is declared as <code>double</code>?</p>
  <hr />
  <p>Real example, I declare <code>double</code> array like that:</p>
  <pre><code>private double[] _cachedProduct;
  </code></pre>
  <p>In one thread I update it like that:</p>
  <pre><code>_cachedProduct[instrumentId] = calcValue;
  //...
  are.Set();
  </code></pre>
  <p>In another thread I read this array like that:</p>
  <pre><code>while(true)
  {
      are.WaitOne();
      //...
      result += _cachedProduct[instrumentId];
      //...
  }
  </code></pre>
  <p>For me it just works fine as is. However to make sure &quot;it will always work&quot; no matter what it seems I should add either <code>Volatile.Write</code> or <code>Interlocked.Exchange</code>. Because <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#96-atomicity-of-variable-references" rel="nofollow noreferrer" title="9.6 Atomicity of variable references">double update is not guaranteed to be atomic</a>.</p>
  <p>In the answer to this question I want to see detailed comparison of <code>Volatile</code> and <code>Interlocked</code> classes. Why we need 2 classes? Which one and when to use?</p>
  <hr />
  <p>Another example, from the implementation of a locking mechanism in an <a href="https://stackoverflow.com/questions/70906823/is-it-safe-to-replace-volatile-write-with-simple-assignment-in-a-method-that-c" title="Is it safe to replace Volatile.Write() with simple assignment in a method that contains only that statement?">in-production project</a>:</p>
  <pre><code>private int _guard = 0;
  
  public bool Acquire() =&gt; Interlocked.CompareExchange(ref _guard, 1, 0) == 0;
  
  public void Release1() =&gt; Interlocked.Exchange(ref _guard, 0);
  public void Release2() =&gt; Volatile.Write(ref _guard, 0);
  </code></pre>
  <p>Does it make any practical difference if the users of this API call the <code>Release1</code> or the <code>Release2</code> method?</p>