Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One really easy way to do this is with a <code>Semaphore</code>. You have one thread that dequeues items and creates threads to process them. For example:</p> <pre><code>const int MaxThreads = 4; Semaphore sem = new Semaphore(MaxThreads, MaxThreads); while (Queue.HasItems()) { sem.WaitOne(); var item = Queue.Dequeue(); Threadpool.QueueUserWorkItem(ProcessItem, item); // see below } // When the queue is empty, you have to wait for all processing // threads to complete. // If you can acquire the semaphore MaxThreads times, all workers are done int count = 0; while (count &lt; MaxThreads) { sem.WaitOne(); ++count; } // the code to process an item void ProcessItem(object item) { // cast the item to whatever type you need, // and process it. // when done processing, release the semaphore sem.Release(); } </code></pre> <p>The above technique works quite well. It's simple to code, easy to understand, and very effective.</p> <p>One change is that you might want to use the <code>Task</code> API rather <code>Threadpool.QueueUserWorkItem</code>. <code>Task</code> gives you more control over the asynchronous processing, including cancellation. I used <code>QueueUserWorkItem</code> in my example because I'm more familiar with it. I would use <code>Task</code> in a production program.</p> <p>Although this does use N+1 threads (where N is the number of items you want processed concurrently), that extra thread isn't often doing anything. The only time it's running is when it's assigning work to worker threads. Otherwise, it's doing a non-busy wait on the semaphore.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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