title: Dispose Unmanaged Resources in Thread
body: <p>I have a class that uses unmanaged resources in a thread, it can also go to sleep when not in use. I am implementing dispose for it, please see example code below (noting it is a dumbed down version of my app). I added while(TheThread.IsAlive()); as disposed could be set to true before DestroySomeUnmangedResouces() has executed. I don't think what I have done is correct so would be grateful if someone could suggest a better model.</p>
  
  <pre><code>protected virtual void Dispose(bool disposing)
  {
      if (!disposed)
      {
          if (disposing)
          {   
              //managed
          }
  
          //unmanged
          _stopTheThread = true;
          startTheThreadEvent.Set();
          while(TheThread.IsAlive());
      }
      disposed = true;
  }
  
  private void TheThread()
  {
      while (!_stopTheThread)
      {
          if (state == State.Stopped)
          {
              // wait till a start occurs
              startTheThreadEvent.WaitOne();
          }
          switch (state)
          {
              case Init: 
                  CreateSomeUnmangedResouces();
                  break;
  
              case Run:       
                  DoStuffWithUnmangedResouces();
                  break;
  
              case Stop:
                  DestroySomeUnmangedResouces();
                  break;
          } // switch
      }
      // Release unmanaged resources when component is disposed
      DestroySomeUnmangedResouces();
  }
  </code></pre>