I'm currently creating a demonstration project to show the rest of my team about how they can use TPL to make better code. However, I'm stumped on a single issue that I figure should be functioning another way; the code:
// Example 7 - Even more exceptions try { var numberList = Enumerable.Range(0, 1000).AsParallel().Select(x => { if (x % 2 == 0) throw new ApplicationException("Shazam!"); return x; }).ToList(); } catch (AggregateException e) { int exceptionsAggregated = 0; e.Flatten().Handle(ex => { if (ex is ApplicationException) { if ((ex as ApplicationException).Message == "Shazam!") exceptionsAggregated++; } return true; }); Console.WriteLine("Exceptions: " + exceptionsAggregated); } What I would except to happen is that the aggregate exception would contain 500 inner exceptions because each other thread invoked in PLINQ would throw an exception. However, I'm only getting 4 exceptions in the Aggregate exception.
My first though was that perhaps TPL terminates the run when it reached a limit on the number of exceptions that could be thrown. However, I can't seem to find any online articles or documentation that would support that claim. So I'm kinda stumped here; what would caused only 4 exceptions to be contained?
Am I just missing something fundamental here?
EDIT: @Dan Bryant below pegged it on the head; when I change the code to the following:
// Example 7 - Even more exceptions
try { var tasks = Enumerable.Range(0, 100).Select(x => Task.Factory.StartNew(() => { if (x % 2 == 0) throw new ApplicationException("Shazam!"); return x; })).ToArray(); Task.WaitAll(tasks); } catch (AggregateException e) { int exceptionsAggregated = 0; e.Flatten().Handle(ex => { if (ex is ApplicationException) { if ((ex as ApplicationException).Message == "Shazam!") exceptionsAggregated++; } return true; }); Console.WriteLine("Exceptions: " + exceptionsAggregated); } I correctly get the right number of exceptions. Problem solved!