且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在这种情况下,为什么使用AsParallel()比foreach慢?

更新时间:2021-10-09 17:45:28

要进行并行计算,您必须具有多个处理器或内核,否则,您只是在线程池中排队等待CPU的任务. IE.单核心计算机上的AsParallel是顺序的,加上线程池和线程上下文切换的开销.即使在两核计算机上,您也可能无法同时获得两个核,因为许多其他事情都在同一计算机上运行.

In order for parallel computation to happen you have to have multiple processors or cores, otherwise you are just queueing up tasks in the threadpool waiting for the CPU. I.e. AsParallel on a single core machine is sequential plus the overhead of threadpool and thread context switch. Even on a two core machine, you may not get both cores, since lots of other things are running on the same machine.

仅当您具有带有阻塞操作(I/O)的长时间运行任务时,真正的.AsParallel()才有用,操作系统可以挂起阻塞线程并让另一个线程运行.

Really .AsParallel() only becomes useful if you have long running tasks with blocking operations (I/O) where the OS can suspend the blocking thread and let another one run.