Unit testing parallel code
Creating unit tests for code that use Parallel.Invoke
, Parallel.For
, Parallel.ForEach
, and Parallel.ForEachAsync
is relatively straightforward. While they can run processes in parallel when conditions are suitable, they run synchronously relative to the invoking code. Unless you wrap Parallel.ForEach
in a Task.Run
statement, the flow of code will not continue until all iterations of the loop have been completed.
The one caveat to consider when testing code that uses parallel loops is the type of exceptions to expect. If an exception is thrown within the body of one of these constructs, the surrounding code must catch AggregateException
. The exception to this Exception
rule is Parallel.ForEachAsync
. Because it is called with async
/await
, you must handle Exception
instead of AggregateException
. Let’s create an example to illustrate these scenarios:
- Create a new Class Library project in Visual Studio named
ParallelExample
. - Rename
Class1...