title: Waiting on a threadpool in C#
body: <h3>Duplicate of</h3>
  <blockquote>
  <p><a href="https://stackoverflow.com/questions/540078/wait-for-pooled-threads-to-complete">Wait for pooled threads to complete.</a></p>
  </blockquote>
  <p>I have X number of functions waiting to be given to a threadpool and the threadpool has a maxnumber of threads as 5.I need to find a solution to make the main thread wait until all the X functions are executed.</p>
  <p>Code looks like this :</p>
  <pre><code>              for(int i=0;i&lt;Rulecnt;i++)
                {
                    int copy = count;
                    ds[copy] = dba.geData(ru[copy]);
                    dcont[copy] = new DataContainer(ru[copy], ds[copy], copy);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(runRule[copy].performTask),dcont[count]);
                }
  </code></pre>
  <p>I want the main thread to wait until all the functions are executed.</p>
  <p>A simple solution is to create Rulecnt no of ManualResetEvents and pass them to the threads, and wait on all the signals to arrive.</p>
  <p>But as the max no of  threads running at any time is 5 , can we just use 5 ManualResetEvents ?,If possible how?</p>
  <p>or if there is any solution plz explain?</p>