Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

How to: Handle Exceptions in Parallel Loops

.NET Framework 4.6 and 4.5

The Parallel.For and Parallel.ForEach overloads do not have any special mechanism to handle exceptions that might be thrown. In this respect, they resemble regular for and foreach loops (For and For Each in Visual Basic); an unhandled exception causes the loop to terminate immediately.

When you add your own exception-handling logic to parallel loops, handle the case in which similar exceptions might be thrown on multiple threads concurrently, and the case in which an exception thrown on one thread causes another exception to be thrown on another thread. You can handle both cases by wrapping all exceptions from the loop in a System.AggregateException. The following example shows one possible approach.

Note Note

When "Just My Code" is enabled, Visual Studio in some cases 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 example below. To prevent Visual Studio from breaking on the first error, just uncheck the "Just My Code" checkbox under Tools, Options, Debugging, General.

In this example, all exceptions are caught and then wrapped in an System.AggregateException which is thrown. The caller can decide which exceptions to handle.

' How to: Handle Exceptions in Parallel Loops 

Imports System.Collections.Concurrent
Imports System.Threading.Tasks

Module ExceptionsInLoops

    Sub Main()

        ' Create some random data to process in parallel. 
        ' There is a good probability this data will cause some exceptions to be thrown. 
        Dim data(1000) As Byte 
        Dim r As New Random()

        Catch ae As AggregateException
            ' This is where you can choose which exceptions to handle. 
            For Each ex As Exception In ae.InnerExceptions
                If (TypeOf (ex) Is ArgumentException) Then
                    Throw ex
                End If 
        End Try
        Console.WriteLine("Press any key to exit.")
    End Sub 
    Sub ProcessDataInParallel(ByVal data As Byte())

        ' Use ConcurrentQueue to enable safe enqueueing from multiple threads. 
        Dim exceptions As New ConcurrentQueue(Of Exception)

        ' Execute the complete loop and capture all exceptions.
        Parallel.ForEach(Of Byte)(data, Sub(d)
                                                ' Cause a few exceptions, but not too many. 
                                                If d < &H3 Then 
                                                    Throw New ArgumentException(String.Format("value is {0:x}. Element must be greater than &H3", d))
                                                    Console.Write(d & " ")
                                                End If 
                                            Catch ex As Exception
                                                ' Store the exception and continue with the loop. 
                                            End Try 
                                        End Sub)

        ' Throw the exceptions here after the loop completes. 
        If exceptions.Count > 0 Then 
            Throw New AggregateException(exceptions)
        End If 
    End Sub 
End Module
© 2015 Microsoft