Handling Exceptions

In single-core scenarios, LINQ queries are executed sequentially. This means that if your code encounters an exception, the exception is at a specific point, and the code can handle it normally. In multicore scenarios multiple exceptions could occur, because more threads are running on multiple processors concurrently. Because of this, PLINQ provides a special way for intercepting and handling exceptions. Such a way is constituted by the AggregateException class that is specific for exceptions within parallelism. Such a class exposes a couple of interesting members, such as Flatten that is a method that turns it into a single exception and InnerExceptions that is a property storing a collection of InnerException objects, each representing one of the occurred exceptions.

Disable Just My Code

In order to correctly catch an AggregateException you need to disable the Just My Code debugging in the debug options, otherwise the code execution will break on the query and will not allow you to investigate the exception.

Consider the following code, in which an array of strings stores some null values and that causes NullReferenceException at runtime:

image

In a single-core scenario a single NullReferenceException is caught and handled the first time the code encounters the error. In multicore scenarios an AggregateException could happen due to multiple threads running on multiple processors; therefore, you cannot control where and how many exceptions can be thrown. Consequently, the AggregateException stores information on such exceptions. The previous code shows how you can iterate the InnerExceptions property.

Summary

Multicore and multiprocessor architectures are part of the real world today. Because of this, .NET Framework 4.0 provides a specific LINQ implementation known as Parallel LINQ that allows scaling query executions over multiple threads and processors so that you can get benefits in improving performances of your code. In this chapter you learned how to invoke the AsParallel method for creating parallelized queries and comparing them to classic LINQ queries. You also saw how to control queries forcing parallelism, implementing cancellation, setting the maximum number of tasks, and handling the AggregateException exception. In Chapter 45 you get more granular information on the Task Parallel Library so that you can have a complete overview of parallel computing with .NET Framework 4.0 and Visual Basic 2010.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.146.23