title: What's the best way of achieving a parallel infinite Loop?
body: <p>I've gotten used to using <code>Parallel.For()</code> in .NET's parallel extensions as it's a simple way of parallelizing code without having to manually start and maintain threads (which can be fiddly). I'm now looking at an infinite loop (do something until I signal it to stop) that I wish to parallelize, there isn't an argument free <code>Parallel.For()</code> overload to do this so was wondering what the best approach here would be. In principle I could just do something like:</p>
  <pre><code>Parallel.For(0, int.Max)
  </code></pre>
  <p>But I'm suspecting that might not be an expected/efficient pattern for the work partitioning logic to handle(?)</p>
  <p>Another option is something like:</p>
  <pre><code>for(;;)
  {
      Parallel.For(0, 128, delegate()
      {
         // Do stuff.
      }
  }
  </code></pre>
  <p>But that seems inelegant and may also result in inefficient work partitioning.</p>
  <p>Right now my instinct is to do this manually by creating and maintaining my own threads, but I would be interested in getting some feedback/opinions on this. Thanks.</p>
  <p>=== UPDATE ===</p>
  <p>I'm using a simplified version of the code from the article in the <a href="https://stackoverflow.com/a/8671900/11178549">accepted answer</a> (I've removed the <code>ParallelOptions</code> parameter). Here's the code...</p>
  <pre><code>public class ParallelUtils
  {
      public static void While(Func&lt;bool&gt; condition, Action body) 
      { 
          Parallel.ForEach(IterateUntilFalse(condition), ignored =&gt; body()); 
      }
  
      private static IEnumerable&lt;bool&gt; IterateUntilFalse(Func&lt;bool&gt; condition) 
      { 
          while (condition()) yield return true; 
      }
  }
  </code></pre>
  <p>An example usage would be:</p>
  <pre><code>Func&lt;bool&gt; whileCondFn = () =&gt; !_requestStopFlag;
  ParallelUtils.While(whileCondFn, delegate()
  {
      // Do stuff.
  });
  </code></pre>