title: Threadpool with endless worker threads
body: <p>I have class which implements an endless worker thread like <a href="https://stackoverflow.com/questions/1567040/proper-way-to-have-an-endless-worker-thread">this</a> example, in my case representing a body. During runtime I will have between 0 and ~8 instances live at any time with instances constantly being created and destroyed.</p>
  
  <p>Most of the time this class has a lifecycle of 30 seconds to 5 minutes but occasionally there may be a number of instances created and destroyed in a relatively short period of time. This is where I tend to run into performance issues given the low spec hardware this code is running on.</p>
  
  <p>I would now like to rewrite the behavior so that I use a ThreadPool for my collection of running workers and I am struggling to find the correct way to structure the code.</p>
  
  <p>Basically the code I have at the moment is something like</p>
  
  <pre><code>public class BodyCollection : IReadOnlyDictionary&lt;ulong, TrackedBody&gt;
  {
      public void Update() 
      {
          if (createNew) 
          {
             var body = new TrackedBody();
             body.BeginTracking();
             this.Add(1234, body);
          }
  
          if (remove) 
          {
              TrackedBody body = this[1234];
              body.StopTracking();
              this.Remove(body);
          }
      }
  }
  
  public class TrackedBody
  {
      private readonly Thread _BiometricsThread;
      private volatile bool _Continue = true;
  
      public TrackedBody() 
      {
          _BiometricsThread = new Thread(RunBiometricsThread);
      }
  
      public void BeginTracking()
      {
          _BiometricsThread.Start();
      }
  
      public void StopTracking() 
      {    
          _Continue = false;
      }
  
      private void RunBiometricsThread()
      {
          while(_Continue) 
          {
              System.Threading.Thread.Sleep(1000);
          }
      }
  }
  </code></pre>
  
  <p>So how do I re-write the above to utilize a ThreadPool correctly and so that I can cancel running threads on the ThreadPool as required? Do I use CancellationTokens or ManualResetEvents to control the threads?</p>