Parallel.For/Foreach 线程重用 C#

Parallel.For/Foreach threads reuse C#

有没有办法重用在 Parallel.ForEach 循环的后续调用中使用的线程?我正在尝试这样做,因为我知道创建线程的成本很高。

这就是我想做的事情:

var collection = CreateMyCollection()
var pool = CreateThreadPool()
for(int i =0 ; i<1000 ; i++)
      Parallel.ForEach(pool, collection, (element) => Calculate(element, i))

可以吗?

注意:我不能并行化外部循环('i's' 之间的硬依赖)

Parallel.ForEach 是 TPL. By default TaskSceduler 的一部分,负责将工作项排队到线程上,将使用 ThreadPool。

An instance of the TaskScheduler class represents a task scheduler. A task scheduler ensures that the work of a task is eventually executed. The default task scheduler is based on the .NET Framework 4 thread pool, which provides work-stealing for load-balancing, thread injection/retirement for maximum throughput, and overall good performance. It should be sufficient for most scenarios. The TaskScheduler class also serves as the extension point for all customizable scheduling logic. This includes mechanisms such as how to schedule a task for execution, and how scheduled tasks should be exposed to debuggers. If you require special functionality, you can create a custom scheduler and enable it for specific tasks or queries.