title: Interlocked.exchange as a lock
body: <p>I'm trying to use <code>Interlocked.Exchange</code> to create a thread safe lock for some object initialize functions. Consider the below code. I want to be sure that the <code>if</code> is doing the same as when the while is substituted. The reason I ask is if the code is run over and over there are times when you get an exit message before the <code>set</code> message. I just would like to confirm that this is just a gui thing since the state on exit always seems to be correct.</p>
  
  <pre><code>class Program
  {
      private static void Main(string[] args)
      {
          Thread thread1 = new Thread(new ThreadStart(() =&gt; InterlockedCheck("1")));
          Thread thread2 = new Thread(new ThreadStart(() =&gt; InterlockedCheck("2")));
          Thread thread3 = new Thread(new ThreadStart(() =&gt; InterlockedCheck("3"))); 
          Thread thread4 = new Thread(new ThreadStart(() =&gt; InterlockedCheck("4")));
          thread4.Start();
          thread1.Start();
          thread2.Start();
          thread3.Start();
  
          Console.ReadKey();
      }
  
      const int NOTCALLED = 0;
      const int CALLED = 1;
      static int _state = NOTCALLED;
      //...
      static void InterlockedCheck(string thread)
      {
          Console.WriteLine("Enter thread [{0}], state [{1}]", thread, _state);
  
          //while (Interlocked.Exchange(ref _state, CALLED) == NOTCALLED)
          if (Interlocked.Exchange(ref _state, CALLED) == NOTCALLED)
          {
              Console.WriteLine("Setting state on T[{0}], state[{1}]", thread, _state);
          }
  
          Console.WriteLine("Exit from thread [{0}] state[{1}]", thread, _state);
      }
  }
  </code></pre>