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 is thrown.
How to do it…
In the
Recipes
class, add a method calledCheckClientMachinesOnline()
that takes as parameters aList<string>
collection of IP addresses and an integer that specifies the minimum number of machines required to be...