title: How to throttle multiple asynchronous tasks?
body: <p>I have some code of the following form:</p>
  
  <pre><code>static async Task DoSomething(int n) 
  {
    ...
  }
  
  static void RunThreads(int totalThreads, int throttle) 
  {
    var tasks = new List&lt;Task&gt;();
    for (var n = 0; n &lt; totalThreads; n++)
    {
      var task = DoSomething(n);
      tasks.Add(task);
    }
    Task.WhenAll(tasks).Wait(); // all threads must complete
  }
  </code></pre>
  
  <p>Trouble is, if I don't throttle the threads, things start falling apart.  Now, I want to launch a maximum of <code>throttle</code> threads, and only start the new thread when an old one is complete.  I've tried a few approaches and none so far has worked.  Problems I have encountered include:</p>
  
  <ul>
  <li>The <code>tasks</code> collection must be fully populated with all tasks, whether active or awaiting execution, otherwise the final <code>.Wait()</code> call only looks at the threads that it started with.</li>
  <li>Chaining the execution seems to require use of <code>Task.Run()</code> or the like.  But I need a reference to each task from the outset, and instantiating a task seems to kick it off automatically, which is what I don't want.</li>
  </ul>
  
  <p>How to do this?</p>