I observed a weird behavior while experimenting with a PLINQ query. Here is the scenario:
- There is a source
IEnumerable<int>sequence that contains the two items 1 and 2. - A Parallel LINQ
Selectoperation is applied on this sequence, projecting each item to itself (x => x). - The resulting
ParallelQuery<int>query is consumed immediately with aforeachloop. - The
selectorlambda of theSelectprojects successfully the item 1. - The consuming
foreachloop throws an exception for the item 1. - The
selectorlambda throws an exception for the item 2, after a small delay.
What happens next is that the consuming exception is lost! Apparently it is shadowed by the exception thrown afterwards in the Select. Here is a minimal demonstration of this behavior:
ParallelQuery<int> query = Enumerable.Range(1, 2)
.AsParallel()
.Select(x =>
{
if (x == 2) { Thread.Sleep(500); throw new Exception($"Oops!"); }
return x;
});
try
{
foreach (int item in query)
{
Console.WriteLine($"Consuming item #{item} started");
throw new Exception($"Consuming item #{item} failed");
}
}
catch (AggregateException aex)
{
Console.WriteLine($"AggregateException ({aex.InnerExceptions.Count})");
foreach (Exception ex in aex.InnerExceptions)
Console.WriteLine($"- {ex.GetType().Name}: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
Output:
Consuming item #1 started
AggregateException (1)
- Exception: Oops!
Chronologically the consuming exception happens first, and the PLINQ exception happens later. So my understanding is that the consuming exception is more important, and it should be propagated with priority. Nevertheless the only exception that is surfaced is the one that occurs inside the PLINQ code.
My question is: why is the consuming exception lost, and is there any way that I can fix the query so that the consuming exception is propagated with priority?
The desirable output is this:
Consuming item #1 started
Exception: Consuming item #1 failed
I think what you are seeing is the result of the compiler translation of the
foreachinto awhile (MoveNext())with atry/finallyto dispose of the enumerator. When the inner exception is thrown, it is caught by the finally and theDispose()of the enumerator causes all theSelectthreads to finish, which causes an exception inside thefinallyblock, which throws away the initial exception as discussed here. You need to use your own loop and atry/catchif you want to prevent this, though I think the Microsoft recommendation would be to use atry/catchin theSelectto be closer to the source of the exception.Here is a modification of your existing code replacing the
foreachwith the compiler generated expansion offoreachusing an enumerator. (I use LINQPad to see the C# 1.0 equivalent code / IL code from the compiler.)You can capture any exceptions during the
Disposeof the enumerator and then bundle them up with the original exception into anAggregateExceptionwhen you catch them.I wrapped the boilerplate into an extension method to replace the normal
foreach:PS The
bvariable and theifprevents the compiler from optimizing out thewhileloop into anifsince it can figure out thethrowwill prevent the loop from executing more than once pass.