Parallel.For/Foreach threads reuse C#

786 views Asked by At

Is there a way to reuse threads used in consecuent calls of Parallel.ForEach loop? I am tring to do because I understand that thread creation can be costly.

Thats what i would like to do:

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

Is it possible?

Note: I cannot parallize the external loop instead (hard dependancy between 'i's')

1

There are 1 answers

1
Johnny On BEST ANSWER

Parallel.ForEach is part of TPL. By default TaskSceduler, responsible for queuing work items onto threads, will use 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.