Parallel.ForEach
LoopSimilarly to For
loops, the Parallel
class offers an implementation of For..Each
loops for iterating items within a collection in parallel. Still taking advantage of methods shown at the beginning of this section for retrieving thread information, simulate intensive processing and measuring elapsed time; imagine you want to retrieve the list of image files in the user level Pictures folder simulating an intensive processing over each filename. This task can be accomplished via a classic For..Each
loop as follows:
The intensive processing simulation still relies on a single thread and on a single processor, thus it will be expensive in terms of time and system resources. Figure 45.3 shows the result of the loop.
Fortunately the Task Parallel Library enables iterating items in a collection concurrently. This is accomplished with the Parallel.ForEach
method, which is demonstrated in the following code:
Parallel.ForEach
is generic and therefore requires specifying the type of items in the collection. In this case the collection is an IEnumerable(Of String)
, so ForEach
takes (Of
String)
as the generic parameter. Talking about arguments, the first one is the collection to iterate, whereas the second one is an Action(Of T)
, therefore a reference to a delegate or a statement lambda like in the preceding example, representing the action to take over each item in the collection. If you run the code snippet, you get the result shown in Figure 45.4.
The difference is evident. The parallel loop completes processing in almost half the time of the classic loop; this is possible because the parallel loop automatically runs multiple threads for splitting the operation across multiple units of work, but particularly it takes full advantage of the multicore processors architecture of the running machine to take the most from system resources.
ParallelLoopState
ClassThe System.Threading.Tasks.ParallelLoopState
enables getting information on the state of parallel loops such as Parallel.For
and Parallel.ForEach
. For example, you can understand if a loop has been stopped via the Boolean property IsStopped
or if the loop threw an exception via the IsExceptional
property. Moreover you can stop a loop with Break
and Stop
methods. The first one requests the runtime to stop the loop execution when possible, but including the current iteration while Stop
does the same but excluding the current iteration. Basically you need to pass a variable of type ParallelLoopState
to the delegate invoked for the loop or let the compiler infer the type as in the following example:
18.188.64.66