title: How To Use TPL to Manage Multiple Indefinite Tasks
body: <p>I have an application that consists of an Engine which manages a number (usually less than 30) of Pollers. The Engine is running in a Windows Service and when it starts it initiates all of the Pollers that have been configured. The Pollers should run continuously as long as the Windows Service is running. The application has been in production for some time, but I am doing some restructuring to it for performance considerations. Previously, I initiated Threads manually so that each poller would run in its own Thread. I would like to use TPL for the added parallelism.</p>
  
  <p>I have gotten it to work by doing a simple Parallel.ForEach() loop. I can kick off each Poller and do a single poll. BTW, each Poller has a configured TimeSpan value for its Frequency which is how long to wait inbetween polls. By default, this value is 5 seconds.</p>
  
  <p>Here's my question. What might be the best way to run each Poller continuously so that they Poll over and over until the Engine is stopped? Here's what I'm using so far. Let me know if this looks like I"m on the right track or if there's an obviously better way. Thanks.</p>
  
  <pre><code>    public void Start()
      {
          Parallel.ForEach(Pollers, p =&gt; InitiatePolling(p));
          running = true;            
      }
  
      private void InitiatePolling(Poller poller)
      {
          Stopwatch watch = new Stopwatch();
          while (running)
          {
              watch.Start();
              poller.Poll();
              while (watch.Elapsed &lt; poller.Frequency); //wait until the alotted frequency
          }
      }
  </code></pre>
  
  <p>EDIT:
  After suggestions, here's my code. It's working good, but I'd like to see if anyone can see any problems with it that I might be overlooking:</p>
  
  <pre><code>    public void Start()
      {
          if (!_initialized) Initialize();
          running = true;
          Parallel.ForEach(Pollers, p =&gt;
          {
              Stopwatch watch = new Stopwatch();
              while (running)
              {
                  watch.Restart();
                  p.Poll();
                  Thread.Sleep(p.Frequency - watch.Elapsed); 
              }
          });
      }
  </code></pre>
  
  <p>Actually, it appears to be working quite well in my initial testing. The processor does not even register the process (switched from a while loop to the Threading.Sleep as suggested). See anything wrong with it as is?</p>