我试图理解 和 之间的Parralel.For
区别ThreadPool.QueueUserWorkItem
。
硬件软件:
- Intel i5(四核)
- Windows 7 64 位教授
- 点网 4.5
案例一代码:线程池
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);
}
输出:
使用线程 10 (45.871) 完成 0 使用线程
11 (45.875)
完成 1 使用线程 12 (45.875)
完成 2 使用线程 13 (45.875)
完成 3 使用线程 10 (46.869) 完成 4
案例2代码: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") + ")"); });
});
输出:
使用线程 10 (16.923) 完成 0 使用线程
11 (16.925)
完成 1 使用线程 12 (16.925)
完成 2 使用线程 13 (16.926)
完成 3 使用线程 14 (16.926 ) 完成 4
问题:
从案例 1 的结果来看,似乎只有四个线程处于活动状态,然后使用第一个空闲线程完成最终任务。在情况 2 中,似乎有五个线程立即专用并“同时”执行。
为什么 QueueUserWorkItem 的线程处理不使用第五个线程,如并行类?
(ThreadPool.GetAvailableThreads(...)
确认有 1023 个工作线程可用)。