title: Disposing of thread with infinite loop
body: <p>I have an infinite loop that is used to consume items from a <code>BlockingCollection</code>. </p>
  
  <pre><code>public class MessageFileLogger
  {
      private BlockingCollection&lt;ILogItem&gt; _messageQueue;
      private Thread _worker;
      private bool _enabled = false;
      public MessageFileLogger()
      {
           _worker = new Thread(LogMessage);
           _worker.IsBackground = true;
           _worker.Start();
      }
  
      private void LogMessage()
      {
          while (_enabled)
          {
              if (_messageQueue.Count &gt; 0)
              {
                  itm = _messageQueue.Take();
                  processItem(itm);
              }
              else
              {
                  Thread.Sleep(1000);
              }
          }
      }
  }
  </code></pre>
  
  <p>which is referenced by another object that gets instantiated every minute or couple of minutes (could be moved out to 1 hour increments or such).</p>
  
  <pre><code>public class Helper
  {
      MessageFileLogger _logger;
      public Helper(string logFilePath, LogMode logMode)
      {
          _logger = new MessageFileLogger(logFilePath, logMode);
          _logger.Enabled = true;
      }
  
      public void foo()
      {
      }
  }
  </code></pre>
  
  <p><strong>Question #1)</strong>
  What can I do to ensure that the thread is exited when the object that references it is no longer needed?</p>
  
  <p>Note: Helper only needs to call foo, so once it no longer needs to call <code>foo</code>, the object can be garbage collected. So, incorporating a using statement with Helper is certainly a possibility.</p>
  
  <p><strong>Question #2)</strong>
  Does <code>_messageQueue</code> need to be disposed? If so, how do I dispose of it without it affecting the <code>LogMessage</code> thread? (I tried disposing of it while the thread was running and <em>no surprise</em> got an error).</p>
  
  <p>I tried extending IDisposable (in MessageFileLogger):</p>
  
  <pre><code>public void Dispose()
  {
     _enabled = false;
     _messageQueue.Dispose();
  }
  </code></pre>
  
  <p>and I haven't had any issues with this but I'm not confident that I just haven't had an issue yet. Also, would this mean that <code>Helper</code> also needs to <code>IDisposable</code> and a using statement needs to be used with <code>Helper</code>?</p>
  
  <p>Note: This question is based on the same code I had with <a href="https://stackoverflow.com/questions/22051545/producer-consumer-producer-using-high-cpu">another question</a> of mine.</p>