Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I recommend using the <a href="http://msdn.microsoft.com/en-us/library/y5htx827.aspx" rel="nofollow noreferrer">ThreadPool</a> for your task. Its algorithm will generally be more efficient than something you can roll by hand.</p> <p>Now the fun part is getting notified when all of your threads complete. Unless you have really specific needs which make this solution unsuitable, it should be easy enough to implement with the <a href="http://msdn.microsoft.com/en-us/library/system.threading.countdownevent.aspx" rel="nofollow noreferrer">CountdownEvent</a> class, which is a special kind of waithandle that waits until its been signaled <code>n</code> times. Here's an example:</p> <pre><code>using System; using System.Linq; using System.Threading; using System.Diagnostics; namespace CSharpSandbox { class Program { static void SomeTask(int sleepInterval, CountdownEvent countDown) { try { // pretend this did something more profound Thread.Sleep(sleepInterval); } finally { // need to signal in a finally block, otherwise an exception may occur and prevent // this from being signaled countDown.Signal(); } } static CountdownEvent StartTasks(int count) { Random rnd = new Random(); CountdownEvent countDown = new CountdownEvent(count); for (int i = 0; i &lt; count; i++) { ThreadPool.QueueUserWorkItem(_ =&gt; SomeTask(rnd.Next(100), countDown)); } return countDown; } public static void Main(string[] args) { Console.WriteLine("Starting. . ."); var stopWatch = Stopwatch.StartNew(); using(CountdownEvent countdownEvent = StartTasks(100)) { countdownEvent.Wait(); // waits until the countdownEvent is signalled 100 times } stopWatch.Stop(); Console.WriteLine("Done! Elapsed time: {0} milliseconds", stopWatch.Elapsed.TotalMilliseconds); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload