Catching errors in parallel foreach loops
With parallel foreach
loops, developers can wrap the loop in a try
catch
statement. Care needs to be taken, however, because the Parallel.ForEach
will throw AggregatedException
, which has the exceptions it encounters over several threads rolled into one.
Getting ready
We will create a List<string>
object that contains a collection of machine IP addresses. The Parallel.ForEach
loop will check the IP addresses to see whether the machines on the other end of the given IP are alive. It does this by pinging the IP address. The method that performs the Parallel.ForEach
loop will also be given the minimum required alive machines as an integer value. If the minimum number of machines alive is not met, an exception ...
Get C# Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.