I'm trying to understand the differences between Parralel.For
and ThreadPool.QueueUserWorkItem
.
Hardware & Software:
Case 1 code: ThreadPool
for (int index = 0; index < 5; index++)
{
ThreadPool.QueueUserWorkItem((indexParam) =>
{
int threadID = Thread.CurrentThread.ManagedThreadId;
Thread.Sleep(1000);
BeginInvoke((Action)delegate { listBox1.Items.Add("Completed " + indexParam.ToString() + " using thread " + threadID.ToString() + " (" + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString("000") + ")"); });
}, index);
}
Output:
Completed 0 using thread 10 (45.871)
Completed 1 using thread 11 (45.875)
Completed 2 using thread 12 (45.875)
Completed 3 using thread 13 (45.875)
Completed 4 using thread 10 (46.869)
Case 2 code: Parallel.For
ParallelLoopResult result = Parallel.For(0, 5, (int index, ParallelLoopState loopState) =>
{
int threadID = Thread.CurrentThread.ManagedThreadId;
Thread.Sleep(1000);
BeginInvoke((Action)delegate { listBox1.Items.Add("Completed " + index.ToString() + " using thread " + threadID.ToString() + " (" + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString("000") + ")"); });
});
Output:
Completed 0 using thread 10 (16.923)
Completed 1 using thread 11 (16.925)
Completed 2 using thread 12 (16.925)
Completed 3 using thread 13 (16.926)
Completed 4 using thread 14 (16.926)
Question:
From the results in case 1, it appears that only four threads are active, after which the first free thread is then used to complete the final task. In case 2, it appears five threads are immediately dedicated and execute 'simultaneously'.
Why does the thread handling for QueueUserWorkItem not use a fifth thread, like the parallel class?
(ThreadPool.GetAvailableThreads(...)
confirms that 1023 worker threads are available).
http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setminthreads%28v=vs.110%29.aspx
In this case, the ThreadPool min worker threads default is 4 - which explains why only 4 threads are used. The documentation states that ThreadPool may decide whether or not to create more threads once the minimum is reached.
When setting the minimum number of worker threads to 5, then 5 threads are created and all tasks complete simultaneously as expected.