Permalink
Fetching contributors…
Cannot retrieve contributors at this time
53 lines (41 sloc) 3.43 KB
title ms.custom ms.date ms.prod ms.reviewer ms.suite ms.technology ms.tgt_pltfrm ms.topic helpviewer_keywords ms.assetid caps.latest.revision author ms.author manager
How to: Handle Exceptions in a PLINQ Query
03/30/2017
.net
dotnet-standard
article
PLINQ queries, how to handle exceptions
8d56ff9b-a571-4d31-b41f-80c0b51b70a5
13
rpetrusha
ronpet
wpickett

How to: Handle Exceptions in a PLINQ Query

The first example in this topic shows how to handle the xref:System.AggregateException?displayProperty=nameWithType that can be thrown from a PLINQ query when it executes. The second example shows how to put try-catch blocks within delegates, as close as possible to where the exception will be thrown. In this way, you can catch them as soon as they occur and possibly continue query execution. When exceptions are allowed to bubble up back to the joining thread, then it is possible that a query may continue to process some items after the exception is raised.

In some cases when PLINQ falls back to sequential execution, and an exception occurs, the exception may be propagated directly, and not wrapped in an xref:System.AggregateException. Also, xref:System.Threading.ThreadAbortExceptions are always propagated directly.

[!NOTE] When "Just My Code" is enabled, Visual Studio will break on the line that throws the exception and display an error message that says "exception not handled by user code." This error is benign. You can press F5 to continue from it, and see the exception-handling behavior that is demonstrated in the examples below. To prevent Visual Studio from breaking on the first error, just uncheck the "Just My Code" checkbox under Tools, Options, Debugging, General.

This example is intended to demonstrate usage, and might not run faster than the equivalent sequential LINQ to Objects query. For more information about speedup, see Understanding Speedup in PLINQ.

Example

This example shows how to put the try-catch blocks around the code that executes the query to catch any xref:System.AggregateException?displayProperty=nameWithTypes that are thrown.

[!code-csharpPLINQ#41] [!code-vbPLINQ#41]

In this example, the query cannot continue after the exception is thrown. By the time your application code catches the exception, PLINQ has already stopped the query on all threads.

Example

The following example shows how to put a try-catch block in a delegate to make it possible to catch an exception and continue with the query execution.

[!code-csharpPLINQ#42] [!code-vbPLINQ#42]

Compiling the Code

  • To compile and run these examples, copy them into the PLINQ Data Sample example and call the method from Main.

Robust Programming

Do not catch an exception unless you know how to handle it so that you do not corrupt the state of your program.

See Also

xref:System.Linq.ParallelEnumerable
Parallel LINQ (PLINQ)