title: Looping infinitely using threads in Windows Service
body: <p>I've seen several posts on SO that are similar to my question, but none of them have solved my problem.  I'm creating a windows service that is going to poll a Redis database every few seconds or so and perform an action based off of the result.  I'd like to create a "thread pool" of sorts so that I can run multiple actions at the same time if I get a result from Redis while another command is being processed (on another thread).</p>
  
  <p>One of my main problems is that when I stop my Windows service, the process still stays alive for ~30 seconds or so instead of closing down.  Here are the relevant code snippets:</p>
  
  <pre><code>Thread Worker;
  IDatabase db = ...;
  AutoResetEvent StopRequest = new AutoResetEvent(false);
  
  protected override void OnStart(string[] args) {
      var poller = new Poller();
      Worker = new Thread(() =&gt; poller.Poll(StopRequest));
      Worker.Start();
  }
  protected override void OnStop() {
      // Signal worker to stop and wait until it does
      StopRequest.Set();
      Worker.Join();
  }
  </code></pre>
  
  <p>Here's an example of the <code>Poller</code> classes <code>Poll</code> method.</p>
  
  <pre><code>public async void Poll(AutoResetEvent finished)
  {
      var res = string.Empty;
  
      while (!finished.WaitOne(1000))
      {
          res = db.StringGet($"task");
          if (!String.IsNullOrEmpty(res))
          {
              ParseAction(res);
          }
  
          db.KeyDelete($"task");
      }
  }
  </code></pre>
  
  <p>So this code (with a lot trimmed out) stays running in the background correctly, and seems to process incoming queries from Redis just fine, but I'm having the issue with the process not closing correctly as I mentioned above.  I'm also not sure if this is the best approach to take for this situation.  I'd love some pointers on better or more "idiomatic" ways to handle this threading issue.</p>
  
  <p>Thanks!</p>