title: How to Stop a Thread at a given point?
body: <p>I was trying to stop some threads, read some things about the proper way to do it gracefully, but I must be doind something wrong because it simply doesn't work. At first I tried without the <code>lock()</code> with <code>_IsRunning</code> being volatile, then tried with the locks. Here is what I've got.</p>
  
  <pre><code>private volatile bool _IsRunning;
  private static readonly object runLock = new object();
  
  public void Start()
  {
      if (_IsRunning == true)
          return;
      _IsRunning = true;
      (new System.Threading.Thread(new System.Threading.ThreadStart(SendLoop))).Start();
  }
  
  public void Stop()
  {
      lock (runLock)
      {
          _IsRunning = false;
      }
  }
  
  private void SendLoop()
  {
      while (_IsRunning)
      {
          lock (runLock)
          {
              if (_sockets.Count &gt; 0)
              {
                  //some stuff
              }
              else
              {
                  System.Threading.Thread.Sleep(10);
              }
          }
      }
  }
  </code></pre>
  
  <p>I set a breakpoint at my <code>while()</code>, and <code>_IsRunnig</code> is still true even though I passed in <code>Stop()</code>.</p>