Information Technology Reference
In-Depth Information
{
if (e.Error is WebException )
tcs.TrySetResult( new byte [ 0 ]);
else
tcs.TrySetException(e.Error);
}
else
tcs.TrySetResult(e.Result);
}
};
wc.DownloadDataAsync( new Uri (url), tcs);
return tcs.Task;
}
A WebException causes a return indicating 0 bytes read, and all other
exceptions are thrown through the normal channels. Yes, this does mean
that you still need to handle what happens when AggregateExceptions are
thrown. It's possible that you merely need to treat those as fatal errors, and
your background tasks can handle all other errors. But you do need to
understand that it's a different kind of exception.
Of course, errors in background tasks create other issues when you use
LINQ syntax. Remember from Item 35 that I described three different par-
allel algorithms. In all cases, using PLINQ makes some changes to the nor-
mal lazy evaluation, and these changes are important for how you must
handle exceptions in your PLINQ algorithms. Remember that usually, a
query executes only as other code requests the items produced by the
query. That isn't quite how it works with PLINQ. Background threads gen-
erate results as they run, and another task constructs the final result
sequence. It's not exactly an eager evaluation. The query results are not
produced immediately. However, the background threads that produce the
results will start as soon as the scheduler allows. Not immediately, but very
soon. Processing any of those items may throw an exception. Now, that
means you must change your exception handling code. In a typical LINQ
query, you can put try / catch blocks around the code that uses the query
results. It's not needed around the code that defines the LINQ query
expression:
var nums = from n in data
where n < 150
select Factorial(n);
 
Search WWH ::




Custom Search