title: Do we need Volatile.Write for single threaded scenarios?
body: <h2>Scenario:</h2>
  
  <p>I have a class which can be called from many threads.
  It is like this:</p>
  
  <pre><code>internal sealed class ThreadLocalMarker : IDisposable
  {
      [ThreadStatic]
      private static int _counter;
  
      private bool _disposed;
  
      public ThreadLocalMarker()
      {
          _counter++;
      }
  
      public static bool Entered =&gt; _counter &gt; 0;
  
      public void Dispose()
      {
          if (_disposed)
          {
              return;
          }
          _counter--;
          _disposed = true;
      }
  }
  </code></pre>
  
  <p>The ThreadStatic variable _counter is used to create a counter variable which will be allocated to every thread calling this class.</p>
  
  <p>Now I had a unit test like this</p>
  
  <pre><code>[Test]
      public void SingleThreadReadsCorrectValue()
      {
          using (new ThreadLocalMarker())
          {
              Assert.IsTrue(ThreadLocalMarker.Entered);
          }
          Assert.IsFalse(ThreadLocalMarker.Entered);
      }
  </code></pre>
  
  <h2>Issue:</h2>
  
  <p>The second assert is failing inconsistently.</p>
  
  <h2>Workarounds:</h2>
  
  <p>My friend suggested that it could be because though Dispose is getting called after the using is exited, the counter value is not incremented timely because the processor reorders operations for optimizations and therefore when Entered is called, the value of _counter is still not decreased.</p>
  
  <p>He suggested I write this in the Dispose():</p>
  
  <pre><code>Thread.VolatileWrite(ref _counter, _counter - 1);
  </code></pre>
  
  <h2>Questions:</h2>
  
  <ol>
  <li>Do I need Volatile.Write since I have only one thread in my test?</li>
  <li>Do I not have to use Volatile.Read when I am reading the _counter value?</li>
  <li>Can I use the volatile keyword for _counter? </li>
  <li>When should we actually use volatiles and do we even need it in this case with ThreadStatic? 
  My idea is we need volatiles when we have many threads accessing the same copy of a variable shared among the threads. But for the _counter variable, it is declared as ThreadStatic, which means "the value of a static field is unique for each thread." So each thread has its own value for _counter.
  In that case isn't the use of volatiles and memory barriers completely unnecessary here since the different threads don't even share the same copy of _counter.</li>
  <li>And finally, why is my test's last Assert failing inconsistently?</li>
  </ol>
  
  <p>Some code examples for questions 2 and 3 would be an added bonus for me!</p>