Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You <em>could</em> do something with PLinq and <a href="http://msdn.microsoft.com/en-us/library/dd383719.aspx" rel="nofollow"><code>WithDegreeOfParallelism</code></a>.</p> <p><code>WithDegreeOfParallelism</code> will limit the number of threads that simultaneously run.</p> <p>The following example shows how to use Plinq to run a number of workers with limited parallelism passing a different object to each worker.</p> <p>It assumes that you start off with a sequence of objects, and you want to pass each of those objects to a worker method:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Demo { class DataForWorker { public int ID; public string Value; }; class Program { Random rng = new Random(); int numberOfThreadsRunning; void Run() { int maxThreads = 8; IEnumerable&lt;DataForWorker&gt; dataForWorkers = getDataForWorkers(); dataForWorkers .AsParallel() .WithDegreeOfParallelism(maxThreads) .ForAll(worker); } IEnumerable&lt;DataForWorker&gt; getDataForWorkers() { // Just return some dummy data. int numberOfDataItems = 30; return Enumerable.Range(1, numberOfDataItems).Select ( n =&gt; new DataForWorker { ID = n, Value = n.ToString() } ); } void worker(DataForWorker data) { int n = Interlocked.Increment(ref numberOfThreadsRunning); Console.WriteLine("Thread " + data.ID + " is starting. #threads now = " + n); Thread.Sleep(rng.Next(1000, 2000)); Console.WriteLine("Thread " + data.ID + " is stopping."); Interlocked.Decrement(ref numberOfThreadsRunning); } static void Main() { new Program().Run(); } } } </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.
 

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