title: How to end a endless looping background thread
body: <p>Experts,</p>
  
  <p>In C# I need to do some endless looping work beside the main (GUI) thread. So, the main thread creates the looping thread and when the main thread reaches a certain point, it should end that loop. Here my code which I know is wrong:</p>
  
  <pre><code>private bool m_MayRun;
  private Thread m_Thread;
  
  void mainthread() //e.g. the Form_Load event
  {
      ...
      m_Thread = new Thread(loopingThread);
      m_Thread.Start();
      ...
      m_MayRun = false; // e.g. later in the Form_Closing event
      m_Thread.Join();
  }
  
  void loopingThread()
  {
      m_MayRun = true;
      while(m_MayRun) // loop until m_MayRun is set to 'false' from the main thread
      {
          DoStuff();
      }
  }
  </code></pre>
  
  <p>The obious wrong bit is the use of the variable 'm_MayRun' which leads to sometimes block the mainthread, especially the 'join' command. In C++ I would declare it atomic but I couldn't find such a thing in C#. This m_MayRun varible is the only one that has to be accessed from the main thread, so I am looking for a simple and beautiful way (without a big overhead) to solve this synchronization issue. Thanks</p>