Information Technology Reference
In-Depth Information
more important as more of our programs must access data on different
machines and more threads are waiting for responses from remote
machines.
Item 37: Construct Parallel Algorithms with Exceptions in Mind
The previous two items blissfully ignored the possibility of anything going
wrong with any of the child threads doing its work. That's clearly not how
the real world works. Exceptions will occur in your child threads, and
you'll be left to pick up the pieces somehow. Of course, exceptions in back-
ground threads increase the complexity in several ways. Exceptions can't
just continue up the call stack across thread boundaries. Instead, if an
Exception reaches the thread start method, that thread gets terminated.
There's no way for the calling thread to retrieve the error, or do anything
about it. Furthermore, if your parallel algorithm must support rollback if
there are problems, you'll have to do more work to understand any side
effects that have occurred and what you should do to recover from those
errors. Every algorithm has different requirements, so there are no uni-
versal answers for handling exceptions in a parallel environment. The
guidelines I provide here are just that: guidelines that you can use to deter-
mine the best strategy for your particular application.
Let's begin with the async download method from the last item. That has
a very simple strategy in that there are no side effects, and the downloads
from all other Web hosts can continue without concern for the one down-
load that is failing. Parallel operations use the new AggregateException
type to handle exceptions in parallel operations. The AggregateException is
a container that holds all exceptions generated from any of the parallel oper-
ations in an InnerExceptions property. There are a couple different ways
to handle the exception in this process. First, I'll show the more general case,
how to handle any errors generated by subtasks in the outer processing.
The RunAsync() method shown in the previous Item uses more than one
parallel operation. That means you may have AggregateExceptions in the
InnerExceptions collection that is part of the AggregateException you
actually catch. The more parallel operations you have, the deeper this nest-
ing can go. Because of the way parallel operations compose with each
other, you may end up with multiple copies of the original exception in the
final collection of exceptions. I modified the call to RunAsync() to process
possible errors:
 
 
Search WWH ::




Custom Search