Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass 2 lists into Parallel.ForEach?

How do I pass 2 lists into Parallel.ForEach?

Example:

List<Person> a = new List<Person>() { new Person(), new Person(), new Person() };
List<Car> b = new List<Car>() { new Car(), new Car(), new Car() };

//PSEUDO CODE
Parallel.ForEach(a, b, (person, car) => {
    //WORK ON person, WORK ON car
});  

I would prefer to avoid encapsulating Person and Car into Object container. Is this possible?

like image 926
PiZzL3 Avatar asked Apr 14 '11 19:04

PiZzL3


People also ask

Does ForEach work in parallel?

ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.

Is parallel ForEach faster than ForEach?

The execution of Parallel. Foreach is faster than normal ForEach.

How do you write parallel ForEach in C#?

To use Parallel. ForEach loop we need to import System. Threading. Tasks namespace in using directive.

Does parallel ForEach use ThreadPool?

Parallel. ForEach uses managed thread pool to schedule parallel actions. The number of threads is set by ThreadPool.


1 Answers

If you're using .NET 4 (which you probably are) and you're trying to pair the first Person with the first Car etc, you can just use Zip:

List<Person> a = new List<Person>() { new Person(), new Person(), new Person() };
List<Car> b = new List<Car>() {} { new Car(), new Car(), new Car() };
var zipped = a.Zip(b, (person, car) => new { person, car });

Parallel.ForEach(zipped, pair => {
    Person person = pair.person;
    Car car = pair.car;
});
like image 84
Jon Skeet Avatar answered Oct 14 '22 15:10

Jon Skeet