The msdn documentation about order preservation in PLINQ states the following about ForAll()
.
The ForAll runs the action in multiple threads, in parallel. At any given moment multiple actions will be running concurrently, and in these circumstances the notion of "order" is not applicable. To run the actions in order you must run them sequentially, and the simplest way to do it is to run them in a single thread. This can be achieved by just enumerating the result of the query in a standard foreach
loop:
var query = Events.AsParallel().AsOrdered();
foreach (var eventItem in query)
{
// do something with the eventItem
}
If you prefer the fluent ForAll
syntax, you can add a static class in your project with the ForEach
extension method below:
public static void ForEach(this IEnumerable source,
Action action)
{
foreach (TSource item in source)
{
action(item);
}
}
And use it like this:
Events.AsParallel().AsOrdered().ForEach(eventItem =>
{
// do something with the eventItem
});
It should be noted though that in the given example the use of Parallel LINQ is redundant. The query Events.AsParallel().AsOrdered()
performs no transformation to the source enumerable, so no actual computation is taking place. You could remove the .AsParallel().AsOrdered()
part and get the same outcome.