CSharp - Parallel LINQ PLINQ Exception

Introduction

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.

Demo

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

class Program/*from   w  ww  .  ja va  2  s  . c om*/
{
    static void Main(string[] args)
    {
         string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        // Parallel LINQ query
        IEnumerable<string> results = codeNames
            .AsParallel()
            .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 => {
                Console.WriteLine(ex.Message);
                return true;
            });
        }
    }
}