Note that there are some explanatory texts on larger screens.

plurals
  1. POManual threads vs Parallel.Foreach in task scheduler
    primarykey
    data
    text
    <p>I have a Windows Service that processes tasks created by users. This Service runs on a server with 4 cores. The tasks mostly involve heavy database work (generating a report for example). The server also has a few other services running so I don't want to spin up too many threads (let's say a maximum of 4). </p> <p>If I use a <code>BlockingCollection&lt;MyCustomTask&gt;</code>, is it a better idea to create 4 Thread objects and use these to consume from the <code>BlockingCollection&lt;MyCustomTask&gt;</code> or should I use <code>Parallel.Foreach</code> to accomplish this? </p> <p>I'm looking at the <a href="http://blogs.msdn.com/b/pfxteam/archive/2010/04/06/9990420.aspx" rel="nofollow">ParallelExtensionsExtras</a> which contains a StaTaskScheduler which uses the former, like so (slightly modified the code for clarity):</p> <pre><code>var threads = Enumerable.Range(0, numberOfThreads).Select(i =&gt; { var thread = new Thread(() =&gt; { // Continually get the next task and try to execute it. // This will continue until the scheduler is disposed and no more tasks remain. foreach (var t in _tasks.GetConsumingEnumerable()) { TryExecuteTask(t); } }); thread.IsBackground = true; thread.SetApartmentState(ApartmentState.STA); return thread; }).ToList(); // Start all of the threads threads.ForEach(t =&gt; t.Start()); </code></pre> <p>However, there's also a <code>BlockingCollectionPartitioner</code> in the same <a href="http://blogs.msdn.com/b/pfxteam/archive/2010/04/06/9990420.aspx" rel="nofollow">ParallelExtensionsExtras</a> which would enable the use of <code>Parallel.Foreach</code> on a <code>BlockingCollection&lt;Task&gt;</code>, like so:</p> <pre><code> var blockingCollection = new BlockingCollection&lt;MyCustomTask&gt;(); Parallel.ForEach(blockingCollection.GetConsumingEnumerable(), task =&gt; { task.DoSomething(); }); </code></pre> <p>It's my understanding that the latter leverages the <code>ThreadPool</code>. Would using Parallel.ForEach have any benefits in this case?</p>
    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.
 

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