【发布时间】:2014-01-08 07:05:11
【问题描述】:
我试图了解Parralel.For 和ThreadPool.QueueUserWorkItem 之间的区别。
硬件和软件:
- 英特尔 i5(四核)
- Windows 7 64 位专业版
- 点网 4.5
案例 1 代码:线程池
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 个工作线程可用)。
【问题讨论】:
标签: .net multithreading parallel.foreach queueuserworkitem