CSharp - Parallel LINQ PLINQ Exception


In PLINQ the data is broken down into partitions, which are then processed independently and concurrently.

It is possible that we encounter more than one exception.

The first exception doesn't stop the other partitions from being processed.

PLINQ gathers up all the exceptions that it finds and wraps them in a System.AggregateException, which is then thrown to your code.

The following code contains a PLINQ query that will throw exceptions.

When enumerating the results, we wrap the foreach loop in a try/catch block that looks for AggregateExceptions.

The AggregateException class has a Handle method that lets you process each exception in turn.

You are passed the exception and must return true if you have handled the exception or false if you cannot handle the exception.


using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

class Program//  w  w w  .  ja v a2s.  co  m
    static void Main(string[] args)
         string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        // Parallel LINQ query
        IEnumerable<string> results = codeNames
            .Select(p => {
                if (p == "Java" || p == "Oracle")
                    throw new Exception(String.Format("Problem with Code {0}", p));
                return p;
        try {
            foreach (string president in results) {
                Console.WriteLine("Result: {0}", president);
        } catch (AggregateException agex) {
            agex.Handle(ex => {
                return true;