- Introduction
- To Multithread or Not to Multithread?
- Multithreading with PLINQ
- Handling Concurrent Exceptions
- Processing Items with Parallel.ForEach
- Summary
Processing Items with Parallel.ForEach
PLINQ introduces iteration control methods like For and ForEach. ForEach accepts an enumerable collection and a generic Action delegate and performs the action on a background thread. The Action can be satisfied with a Lambda expression:
Parallel.ForEach(results, r=>Console.WriteLine(r));
In the fragment results is the input argument from the LINQ query in Listing 1. The argument r=>Console.WriteLine(r)); writes the anonymous type—the type created in the select clause of Listing 1—to the console.
Lambda expressions are condensed anonymous delegates. The left side of the => ("goes to" operator) represents the function header and input arguments, and the right side represents the function body and statements. The Lambda expression is simply read (or understood) as "Given a value r, write that value to the console."